Shane Grant
Shane Grant

Reputation: 2654

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

I have two tables:

Clients (id, clientname) Projects (id, clientid, projecttitle) 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

Upvotes: 3

Views: 1095

Answers (1)

RPM1984
RPM1984

Reputation: 73112

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.

Upvotes: 4

Related Questions