使用更新实体框架外键 [英] Update foreign key using Entity Framework

查看:258
本文介绍了使用更新实体框架外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我又遇到了与实体框架唷问题....

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

我试图更新外键的表,

我曾与插入问题,但得到了由编辑EDMX文件进行排序。

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,

参照完整性约束冲突发生:一个属性,是参照完整性约束的一部分,当物体具有非临时密钥不能更改

任何反馈将是非常有益的。

Any feedback will be very helpful.

问候,

审计局

推荐答案

我不知道,但你可能要检查您是否已经勾选在模型中包含外键列创建/更新您在设计模型。如果您有打勾,你可能会发现,这是不够的设定的目标,则可能需要设置ID以及或仅设置ID。

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.

就个人而言,我不剔包括外键列在模型,因为它给我带来的种种烦恼,我不记得确切,因为它是一年或更前。这是一个痛苦,有时,因为它是好的,能够通过使用IDS来过滤/搜索/更新,但我已经学会了生活没有了,以避免烦恼,如您遇到。

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.

这篇关于使用更新实体框架外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆