0

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

3
  • Make changes to myExistingObject .. then, _dbContext.Save() Commented Feb 18, 2020 at 22:33
  • @Jawad but can I somehow re-attach Entity Framework to completely new object? Commented Feb 18, 2020 at 22:35
  • You should not keep two instanced of the same entity tracked at the same time. Either one of the object is your DTO then you need to map the properties from A to B (you could use automapper for this) or you should not have instantiated the second object in the first place. If you provide us with some code we can help better. Commented Feb 18, 2020 at 22:54

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.