Save a complex object with Entity Framework

2

The system has a Orders 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 Pedido and ItensDePedido .

My question is: does the Entity Framework know how to differentiate a Item Novo from a item Editado ?

I explain better, see the user accesses the Order screen (makes new order) and adds items to the order and then clicks Save and the system adds all the items to the Order, in this situation no doubt:

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

The problem is when the request is changed because the user can add new items to that request and as he had spoken the object _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 the Entity Framework handle this? or do I have to handle this in the code?

    
asked by anonymous 27.09.2016 / 17:25

1 answer

1
  

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

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

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

Now when you do a UPDATE the context has to know which object you have changed, so it maps all the properties of the object in the proxy, so a query to the database must be performed and mapped for context, an example would be;

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

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

Reference 1

Reference 2

Reference 3

    
27.09.2016 / 17:47