I have an existing record from database that I have retrieved using Entity Framework:
MyDataObject myExistingObject= _dbContext.data .Where(s => s.Id == myId).FirstOrDefaultAsync();
Externally, I have received another
MyDataObject newDataObjectForSameRow that contains updated information for
myExistingObject – all fields except Primary Key, that is initially set to 0 in the newDataObjectForSameRow.
How can I instruct Entity Framework “replace the row that has currently myExistingObject by newDataObjectForSameRow, however keeping the same Primary Key”?
Try to use below code:
newDataObjectForSameRow.Id = myId; MyDataObject myExistingObject = _dbContext.data.Where(s => s.Id == myId).FirstOrDefaultAsync(); _dbContext.Entry(myExistingObject).CurrentValues.SetValues(newDataObjectForSameRow); _dbContext.SaveChanges();