开发者

C# Entity Framework: How do I update a record and change foreign key reference?

I have two tables:

Clients (id, clientname) Projects (id, clientid, pr开发者_如何学Pythonojecttitle) foreign key reference clientid -> clients.id

When I load a project with EF like this:

thisProject = (from p in dataEntity.projects.Include("client")
               where p.id == INTVALUE
               select p).FirstOrDefault();

Then I change some values in thisProject, and would like to change the relationship to a diferent client, it will not allow me to modify the clientid field in the Projects table.

Hope I explained this well enough, thanks


You need to do something like this:

var thisProject = (from p in dataEntity.projects.Include("client")
               where p.id == INTVALUE
               select p).FirstOrDefault();

var newClient = dataEntity.clients.FirstOrDefault(); // change to suit
thisProject.Client = newClient;

You can't just change the EntityKey AFAIK - you need to actually change the navigational reference.

HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜