c# – DbEntityEntry.State vs DbPropertyEntry.IsModified

Question:

I have a question about these two ways to specify if an entity has been modified. I usually use DbEntityEntry.State with EntityState.Modified when I make a very big change to the model and want all of them to be persisted in the database, and I use DbPropertyEntry.IsModified with true when I want to specify that only one property has been modified.

So suppose I have a model and I update several properties of it (but not all) of it during a process. Then mark the model (and not the modified properties) as EntityState.Modified through the DbEntityEntry.State property.

When I apply the changes through DbContext.SaveChangesAsync() all the model properties be updated in the database or only the ones that were actually modified? Will an SQL UPDATE command be generated that will include all the model fields in the update?

Answer:

When I apply the changes through DbContext.SaveChangesAsync() all the model properties be updated in the database or only the ones that were actually modified?

All properties are updated unless you specify which ones will not be, like this:

var entry = context.Entry(obj);
entry.State = EntityState.Modified;
foreach (var nome in new[] { "Prop1", "Prop2", "Prop3" })
{
    entry.Property(nome).IsModified = false;
}

Will an SQL UPDATE command be generated that will include all the model fields in the update?

If you don't specify which ones should be excluded (or included), yes. It will be with all fields.

If you want to specify exactly which fields will be updated, use the following boilerplate:

db.Entidades.Attach(entidade);
db.Entry(entidade).Property(x => x.Prop1).IsModified = true;
db.Entry(entidade).Property(x => x.Prop2).IsModified = true;
db.Entry(entidade).Property(x => x.Prop3).IsModified = true;
db.SaveChanges();
Scroll to Top