EntityState - How it works

0

What would the EntityState EntityState serve?

When can it be applied? Do you have any examples of why use it?

    
asked by anonymous 30.04.2017 / 14:00

1 answer

3

To understand how EntityState works you have to understand the Entity Lifecycle.

Any CRUD operation is done through the context we created from the database. This context keeps a reference to all objects and their modifications to the properties (change tracking).

So when you take an existing object out of context it becomes an entity and its state is monitored. If you modify the entity by editing its properties and you move it to the modified state. Then save the changes in context and it in the database.

Usage examples

Adding a new entity to the context:

var cliente = new Cliente { Name = "Marcos" }; 
context.Entry(cliente).State = EntityState.Added; 
context.SaveChanges(); 

Adding an entity to the context that is not being monitored by it:

context.Entry(ClienteExistente).State = EntityState.Unchanged; 

Adding an entity's modifications to the context

context.Entry(ClienteExistente).State = EntityState.Modified;

Change the state of the entity (you can change it)

// Mudando para unchanged
context.Entry(existingBlog).State = EntityState.Unchanged; 

Finally, remember that using EntityState is not explicitly mandatory, you can use it only when necessary.

    
30.04.2017 / 14:42