Entity Framework: Setting a Foreign Key Property

情到浓时终转凉″ 提交于 2019-11-27 12:11:17
Pieter Breed

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

What I've been doing to make things easy is adding the foreign key property myself in the partial class:

public int UserID
{
   get
   {
      if (this.User != null)
         return this.User.UserID;
   }
   set 
   {
      this.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", value);
   }
}

You could make an extension method that constructs the entity based on these ID's.

Using an EntityKey solves your problem ;)

alk.

another method if you don't mind 'polluting' you db schema is to add a computed column, e.g. if you had a foreign key field FK_Customer you could define a new computed column FK_Customer_Computed which has the expression FK_Customer. When you generate\update your edmx model the field will appear like a regular field that you can then reference from you entity object.

Or wait for EF4 :)

Following on from Dylan's answer, Alex James has written a blog on precisely this, explaining the problem in full and how to go about the partial class + property solution.

Faking Foreign Keys - EF3.5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!