简体   繁体   中英

Update foreign key using Entity Framework

I have again ran into problems with Entity Framework phew....

I am trying to update a table with a foreign key,

I had problems with Inserting but that got sorted by editing the edmx file.

I am using the following code to update User table which has a foreign relationship to role table,

Domain.Data.Role role = db.Role.FirstOrDefault(r => r.RoleName == user.Role); 

Domain.Data.User data = db.User.Where(u => u.UserName == username).First();

data.Pass = user.Password.Encrypt();
data.CreatedBy = Login.User.Encrypt();
data.DtCreated = DateTime.Now;

//data.Role = role;

 data.Role = (from r in db.Role
              where r.RoleName == user.Role
              select r).First();

 db.SaveChanges();

On updating I am getting the following exception,

A referential integrity constraint violation occurred: A property that is a part of referential integrity constraint cannot be changed when the object has a non-temporary key.

Any feedback will be very helpful.

Regards,

Sab

I'm not sure, but you might want to check you whether you have ticked "Include foreign key columns in the model" when creating / updating your model in the designer. If you have that ticked, you might find that it isn't enough to set the object, you might need to set the Id as well or only set the id.

eg. you might need to do :

data.RoleId = role.RoleId;

In conjunction with setting the object or instead of setting the object.

Personally, I don't tick "Include foreign key columns in the model" as it caused me all sorts of headaches which I don't recall exactly as it was a year or more ago. It is a pain sometimes, as it is nice to be able to filter / search / update by using Ids, but I have learned to live without that so as to avoid annoyances such as you are experiencing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM