I have a problem with entity framework code first six working so disconnected. The problem occurs when I want to mark an entity as modified, the entity has association properties loaded with a new instance of DbContext, to be more precise the source of my hit and then get the save.
public List<Venta> Get(Expression<Func<Venta, bool>> predicate)
{
try
{
int num = 0;
List<Venta> ventas = new List<Venta>();
using (_context = new MyContext(MyContext.GetConnectionString()))
{
if (predicate == null)
ventas = _context.Ventas.Include("Mesa").Include("Usuario").Include("Pago").ToList();
else
ventas = _context.Ventas.Include("Mesa").Include("Usuario").Include("Pago").Where(predicate).ToList();
}
//I use the other repo to load related entities
UsuarioRepository userRepo = new UsuarioRepository();
foreach (Venta item in ventas)
{
item.GetType().GetProperty("Usuario").SetValue(item, userRepo.Get(u => u.Id == item.UsuarioId).First(), null);
}
//I use the other repo to load related entities
ProductoRepository prodRepo = new ProductoRepository();
foreach (VentaProducto item in ventas.SelectMany(vta => vta.Detalle).ToList())
{
Producto p = prodRepo.Get(prod => item.ProductoId == prod.Id).First();
item.GetType().GetProperty("Producto").SetValue(item, p, null);
}
ventas.ForEach(vta => vta.State = DomainEntityState.Unchanged);
return ventas;
}
catch (Exception ex)
{
throw new Exception("Error al traer las Ventas", ex);
}
}
public override int Save(Venta venta)
{
int saves = 0;
EntityState state;
EntityState stateProducto;
//New Instance of the context without entities in the DbSet's
using (MyContext context = new MyContext(MyContext.GetConnectionString()))
{
try
{
if (venta.IsNewEntity) //Venta nueva
{
state = EntityState.Added;
stateProducto = EntityState.Modified;
}
else
{
state = EntityState.Modified;
stateProducto = EntityState.Modified;
}
//int usuarios = context.Usuarios.Local.Count; //I get 0
//int productos = context.Productos.Local.Count; //I get 0
//int ventasProductos = context.VentasProducto.Local.Count; // I get 0
venta.Usuario = null;
if (venta.Pago != null)
venta.Pago.Usuario = null;
if (venta.Pago != null)
{
EntityState estadoPago = context.GetEntityState(venta.Pago);
}
//HERE IS THE PROBLEM
context.SetEntityState(venta, state);
saves = context.SaveChanges();
}
catch (Exception ex)
{
throw new Exception("Error al grabar la venta", ex);
}
}
return saves;
}
Finally I get the following error ....
Attaching an entity of type 'Jackie.Domain.Entities.Usuario' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
The most strange is that if I load all entities with the same instance of context does not have that problem. It will be a bug? No longer think of anything more. Thank you all. Made with google translator.