Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Entity Framework: Setting a Foreign Key Property

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This missing feature seems to annoy a lot of people.

  • Good news: MS will address the issue with .NET 4.0.
  • Bad news: for now, or if you're stuck on 3.5 you have to do a little bit of work, but it IS possible.

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...