Home » c# » c# – Update a record in Entity Framework Core-Exceptionshub

c# – Update a record in Entity Framework Core-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

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”?

How to&Answers:

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();