Entitystate - How it works

Asked

Viewed 318 times

1

What would be and what is the Entity Framework Entitystate for?

When can it be applied? Someone has some example of why to use it?

1 answer

5


To understand how Entitystate works you have to understand the life cycle of the entity (Entity Lifecycle).

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

So when you take an existing object from the context, it becomes an entity and has its state monitored. If you modify the entity by editing its properties, you pass it to the modified state. Then save the changes in context and it in the database.

Examples of use

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, it is worth remembering that the use of Entitystate explicitly is not mandatory, you can use only when necessary.

  • 1

    What is the advantage of using it? For example, in the first item, you would not apply the same: Client cli = new Client(); cli.name = txtNome.Text; cli.email = txtEmail.Text; Client c = ctx.Clientes.Add(cli); ctx.Savechanges();

  • 1

    What would an example update with Entitystate look like? (where I want to update only 1 field, for example)

  • 1

    Still would. The Add command is doing the same thing as that command. You are working with the entity state in the same way. The issue is not advantage or disadvantage but understand how the Entity Framework works.

  • Got it, it has to put an example of updating a field in the model you mentioned above: context. Entry(Existing clientele). State = Entitystate.Modified;

  • You will change as many properties as you want in the view and controller you use the example I gave "adding modifications...) followed by a context.Savechages()

  • If you want a full example I can show you in chat

  • Hi Yes, because I did an example update and it’s working, and I would like to know the way to do via Entitystate.Modified and the technical difference or in performance of one pro another!

Show 3 more comments

Browser other questions tagged

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