C # Entity Framework: how to update record and change foreign key link?

I have two tables:

Clients (id, clientname) Projects (id, clientid, projecttitle) link to the clientid foreign key → clients.id

When I load a project with EF as follows:

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

Then I change some values ​​in this project and want to change the attitude towards another client, it will not allow me to change the clientid field in the Projects table.

Hope I explained it well enough, thanks

+3
source share
1 answer

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 EntityKey AFAIK - you really need to change the navigation link.

NTN.

+4
source

Source: https://habr.com/ru/post/1774884/


All Articles