为什么 EF 尝试添加新记录而不是编辑?
我有以下代码:
var currentUser = (from i in _dbContext.Users
where i.FirstName == user.FirstName && i.LastName == user.LastName
&& i.Title == user.Title && i.Company == user.Company
select i).FirstOrDefault();
currentUser.Company = user.Company;
currentUser.CompanyUrl = user.CompanyUrl;
currentUser.Country = user.Country;
_dbContext.SaveChanges();
但我收到错误
{“违反 UNIQUE KEY 约束 'IX_Users'。无法插入 对象“dbo.Users”中存在重复键。重复的键值为 (a8, b8, c8)。\r\n该语句已终止。"}
因此,它表示 EF 尝试添加新记录而不是编辑当前记录。为什么?
I have the following code:
var currentUser = (from i in _dbContext.Users
where i.FirstName == user.FirstName && i.LastName == user.LastName
&& i.Title == user.Title && i.Company == user.Company
select i).FirstOrDefault();
currentUser.Company = user.Company;
currentUser.CompanyUrl = user.CompanyUrl;
currentUser.Country = user.Country;
_dbContext.SaveChanges();
but I got an error
{"Violation of UNIQUE KEY constraint 'IX_Users'. Cannot insert
duplicate key in object 'dbo.Users'. The duplicate key value is (a8,
b8, c8).\r\nThe statement has been terminated."}
so, it says that EF tries to add new record instead of edit current. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题在于将
user
和currentUser
结合起来。它很可能会更新您的currentUser
,但同时插入user
。原因可能是这样的:如果公司具有用户导航属性,并且如果您使用 POCO 模板,则这会将
Company
和user
作为新实体连接到上下文。试试这个:
I think the problem will be combining
user
andcurrentUser
. It most probably updates yourcurrentUser
but in the same time insertsuser
. The reason can be this:If company has Users navigation property and if you are using POCO template this will connect both
Company
anduser
as new entities to the context.Try this: