Monday, May 24, 2021

How to update only one field using EF Core?

This method is useful When you are trying to update some record in the table while you are not tracking that entity. 

If you are using tracking then EF is smart enough to update only certain fields. 

Below is the code.


var book = new Book() { Id = bookId, Price = price };
_dbContext.Books.Attach(book);
_dbContext.Entry(book).Property(x => x.Price).IsModified = true;
await _dbContext.SaveChangesAsync();
//// then detach it
_dbContext.Entry(book).State = EntityState.Detached;
This will generate a sql like below
UPDATE dbo.Book SET Price = @Price WHERE Id = @bookId

No comments:

Post a Comment