Save a complex object with Entity Framework

Asked

Viewed 318 times

2

The system has an Order screen where you can add new items or change items from that order.

The object that is sent to the Repository layer is a complex object 1 x N, that is to say Pedido and ItensDePedido.

My question is this: the Entity Framework knows how to differentiate a Item Novo of a item Editado ?

I explain better, see the user access the Order screen (make new order) and add items to the order and then click Save and the system adds all items to the Order, in this situation no doubt:

_repositorio.Pedidos.Add(_pedido);
_repositorio.SaveChanges();

The problem is when the order is changed, because the user can add new items to this request and as the object had said _pedido is a complex object there may be items that already exist in the database and items that do not exist.

_repositorio.Entry(_pedido).State = EntityState.Modified;
_repositorio.SaveChanges();

Should Entity Framework handle this ? or should I handle it in the code ?

1 answer

1


My question is this: the Entity Framework knows how to differentiate an Item New to an Edited Item ?

If you create an object Requests new and attach it in context, the Entity Framework will know that this object is a new object and must be included in the bank, this is formalized through the introduction _repositorio.Pedidos.Add and finalized with the _repositorio.SaveChanges();

Pedidos _pedido = new Pedidos();
_repositorio.Pedidos.Add(_pedido);
_repositorio.SaveChanges();

When you make one UPDATE the context has to know which object you are changing, for that it maps all properties of the object in the proxy, for that a query to the database must be performed and mapped to the context, an example would be;

using (var ctx = new dbContext())
{
    var Pedido = ctx.Pedidos.FirstOrDefault(p => p.Pedido == 1);
    Pedido.Nome = "LCH .... ";
    ctx.SaveChanges();
}

Namely the ctx.Pedidos.FirstOrDefault(p => p.Pedido == 1); materialize the object in context, when it is called the ctx.SaveChanges(); a query is mounting with the update country Nome;

Reference 1

Reference 2

Reference 3

Browser other questions tagged

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