I'm doing a project on asp.net, web form, and I need help with this:
System.InvalidOperationException:An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
This exception occurs when I try to add an element to DbContext
.
Entities are Usuario
, Producto
, ProductoDePedido
, Pedido
.
[Table("Productos")]
public class Producto
{
public int ProductoId { get; set; }
public string Nombre { get; set; }
}
[Table("Pedidos")]
public class Pedido
{
[Key]
public int PedidoId{ get; set; }
public string UsuarioId { get; set; }
public virtual Usuario Usuario { get; set; }
public virtual ICollection<ProductoDePedido> ProductosDePedido { get; set; }
}
[Table("ProductosDePedidos")]
public class ProductoDePedido
{
[Key]
public int ProductoDePedidoId { get; set; }
public int PedidoId { get; set; }
public virtual Pedido Pedido { get; set; }
public int ProductoId { get; set; }
public virtual Producto Producto { get; set; }
}
When I try to add a new order, the exception occurs, this is the method where I add it:
public Pedido CrearPedido(Usuario usuario)
{
ProyectoDbContext context = new ProyectoDbContext();
Pedido pedido = new Pedido
{
Usuario = usuario,
};
context.Pedidos.Add(pedido);
}
The question is that I have no idea why this exception occurs. I had several instances of the DBContext open but before calling the method, I did .Dispose () all.