Successfully added
EF Core
by Marlon
Update Only One Column in EF Core
To only update one field, we can simply change the update method to the following:
Person person = new Person {Id=4, Lastname="Miller"};
dbContext.Attach(person);
dbContext.Entry(person).Property(p => p.Lastname).IsModified = true;
dbContext.SaveChanges();
The above function first constructs the object with the specified Id
and updated Lastname
, and then appends the object; it then explicitly marks the Lastname
property as modified.
The generated UPDATE statement now looks like this
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (8ms) [Parameters=[@p1='?' (DbType = Int32), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
UPDATE `Persons` SET `Lastname` = @p0
WHERE `Id` = @p1;
SELECT ROW_COUNT();
As shown in the EFCore log, only the Lastname
field is updated.
This approach can slightly improve performance because the SQL statement is smaller and the query execution on the database server can be faster.
See also the discussion at Stack Overflow How to update not every fields of an object using Entity Framework and EntityState.Modified
Referenced in:
Leave a Comment
All fields are required. Your email address will not be published.
Comments