为什么 EF 尝试添加新记录而不是编辑?

发布于 2025-01-02 07:36:49 字数 775 浏览 3 评论 0原文

我有以下代码:

        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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

远昼 2025-01-09 07:36:49

我认为问题在于将 usercurrentUser 结合起来。它很可能会更新您的currentUser,但同时插入user。原因可能是这样的:

currentUser.Company = user.Company;

如果公司具有用户导航属性,并且如果您使用 POCO 模板,则这会将 Companyuser 作为新实体连接到上下文。

试试这个:

var currentUser = ...;

var company = new Company { Id = user.Company.Id };
_dbContext.Companies.Attach(company);

currentUser.Company = company;
...

_dbContext.SaveChanges();

I think the problem will be combining user and currentUser. It most probably updates your currentUser but in the same time inserts user. The reason can be this:

currentUser.Company = user.Company;

If company has Users navigation property and if you are using POCO template this will connect both Company and user as new entities to the context.

Try this:

var currentUser = ...;

var company = new Company { Id = user.Company.Id };
_dbContext.Companies.Attach(company);

currentUser.Company = company;
...

_dbContext.SaveChanges();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文