Entity Framework - What is the difference between With Entitystate.Modified and Without Entitystate.Modified?

Asked

Viewed 1,657 times

6

What’s the difference between the two ?

With Entitystate:

var registro = db.MinhaTabela.Where(a => a.MeuCampo == "Valor_Antigo").FirstOrDefault();
registro.MeuCampo = "Valor_Novo";
db.Entry(registro).State = EntityState.Modified;
db.SaveChanges();

Sem Entitystate:

var registro = db.MinhaTabela.Where(a => a.MeuCampo == "Valor_Antigo").FirstOrDefault();
registro.MeuCampo = "Valor_Novo";
db.SaveChanges();

Looks like they both work the same thing or it’s different ?

  • 4

    Entry is for objects that are not in context, your first example is not used, because, it does not need to be so, the second is because the object is in context and all changes can be confirmed with SaveChanges. An example is in MVC when the object is for change and it is not in context, so you need to use Entry and say that it is a change.

  • 2

    @Virgilionovic, thank you for your comment. Helped me a lot.

1 answer

5


The State informs the Entity Framework the state of its object. In its first example, it is not necessary to set the State: Entity Framework itself will do it for you.

But in case you are "disconnected" from the database, that is, create an object out of context, as @virgilionovic mentioned in the comment, you can use the State to inform what the Entity Framework will do to the object when trying to save it.

Anyway, this has an drawback: all attributes will be changed. In the second example, the Entity Framework did the tracking of your object, and know that only need update "Meucampo", while in the first, all fields will be updated, even if they have not been changed. In addition to changing unnecessary fields, it may have other consequences, if for example your bank has constraints in some of the fields that will be validated, making the update process slower.

  • 4

    Just one correction: I don’t know what version you’re talking about, but in version 6 of the Entity Framework this behavior of "updating everything" is not quite like that. The framework He’s smart enough to know which camps were modified in both cases. In addition, when the entity is detached from the context, yes, that’s right: when informing the EntityState, the context checks the entity and begins to observe it.

  • 3

    @Gypsy omorrisonmendez is true, well pointed out. We also have to remember the property AutoDetectChangesEnabled, if set to false can change the way Entity Framework detects changes.

Browser other questions tagged

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