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?
I think the problem will be combining
userandcurrentUser. It most probably updates yourcurrentUserbut 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
Companyanduseras new entities to the context.Try this: