DbEntityEntry.State vs DbPropertyEntry.IsModified

3

I have a question about these two ways of specifying whether an entity has been modified. I usually use DbEntityEntry.State with EntityState.Modified when I make a very big change in the model and I want all of them to be persisted in the database, and I use #

So assuming I have a model and I update several properties of it (but not all) during a process. Then it marks the model (and not the modified properties) as DbPropertyEntry.IsModified through the true property.

When I apply the changes through EntityState.Modified will all the properties of the model be updated in the database or only those that have been modified? Will an UPDATE SQL command be generated that will include all the model fields in the update?

    
asked by anonymous 14.02.2016 / 21:54

1 answer

2
  

When I apply the changes through DbContext.SaveChangesAsync() will all the properties of the model be updated in the database or only those that have been modified?

All properties are updated, unless you specify which ones will not be as follows:

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

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

If you do not specify which ones should be excluded (or included), yes. It will be with all the fields.

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

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();
    
15.02.2016 / 03:46