Entity Framework: Setting a Foreign Key Property

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

Leave a Comment