简体   繁体   English

使用实体框架更新外键

[英]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. 我在插入时遇到问题,但是通过编辑edmx文件进行了排序。

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. 如果勾选了该复选框,则可能会发现仅设置该对象是不够的,您可能还需要设置ID或仅设置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. 有时会很痛苦,因为能够使用IDs进行过滤/搜索/更新是一件很不错的事,但是我学会了没有这种生活,以免遇到您遇到的烦恼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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