We have a table that looks roughly like this:
CREATE TABLE Lockers
{
UserID int NOT NULL PRIMARY KEY (foreign key),
LockerStyleID int (foreign key),
NameplateID int (foreign key)
}
All of the keys relate to other tables, but because of the way the application is distributed, it's easier for us to pass along IDs as parameters. So we'd like to do this:
Locker l = new Locker {
UserID = userID,
LockerStyleID = lockerStyleID,
NameplateID = nameplateID
};
entities.AddLocker(l);
We could do it in LINQ-to-SQL, but not EF?
If you want the foreign key to reference a property other than the primary key, you can use the Fluent API to configure the principal key property for the relationship. The property that you configure as the principal key will automatically be set up as an alternate key.
When you change the relationship of the objects attached to the context by using one of the methods described above, Entity Framework needs to keep foreign keys, references, and collections in sync.
To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the foreign key table.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.
This missing feature seems to annoy a lot of people.
You have to do it like this:
Locker locker = new Locker();
locker.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", userID);
locker.LockerStyleReference.EntityKey = new EntityKey("entities.LockerStyle", "ID", lockerStyleID);
locker.NameplateReference.EntityKey = new EntityKey("entities.Nameplate", "ID", nameplateID);
entities.AddLocker(locker);
entities.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With