Entity Framework - What's the difference between EntityState.Modified and Sem EntityState.Modified?

4

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();

Does it seem like the two work the same thing or is it different?

    
asked by anonymous 03.02.2017 / 05:17

1 answer

4

State tells Entity Framework the state of its object. In your first example, you do not need to set State : the Entity Framework itself will do this for you.

But in case of being "disconnected" from the database, that is, creating an object out of context, as @virgilionovic mentioned in the comment, you can use State to inform you what the Entity Framework will do with the object at try to save it.

Anyway, this has a drawback: all attributes will be changed. In the second example, the Entity Framework has tracking of its object, and knows that it only needs to update "MyField", while in the first, all fields will be updated, even though they have not been changed. In addition to changing unnecessary fields, it can have other consequences, for example your bank has constraints in some of the fields that will be validated, making the update process slower.

    
06.02.2017 / 16:25