Dbentityentry.State vs Dbpropertyentry.Ismodified

Asked

Viewed 93 times

3

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

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

When I apply the changes through the DbContext.SaveChangesAsync() all model properties will be updated in the database or only those that have actually been modified? A SQL UPDATE command will be generated that will include all fields in the model in updating?

1 answer

2


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

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

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

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

If you do not specify which should be deleted (or even included), yes. It will be with all 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();
  • 2

    Vlw, you cleared my doubt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.