System.InvalidOperationException: An entity object can not be referenced by multiple instances of IEntityChangeTracker

0

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.

    
asked by Mr.K 14.08.2017 в 16:45
source

1 answer

1

The problem is that usuario has been obtained in a DbContext different from the one you are trying to add.

There are two possible solutions:

The first would be to remove the user from the same ProyectoDbContext

public Pedido CrearPedido(Usuario usuario)
{
    using (var context = new ProyectoDbContext())
    {
        var usuarioExistente = context.Usuarios.Find(usuario.UsuarioId);

        var pedido = new Pedido
        {
            Usuario = usuarioExistente
        };

        context.Pedidos.Add(pedido);
    }
}

The other would be to include only the IdUsuario in the order, which will make it associate with the correct user when saving the changes.

public Pedido CrearPedido(Usuario usuario)
{
    using (var context = new ProyectoDbContext())
    {
        var pedido = new Pedido
        {
            UsuarioId = usuario.UsuarioId
        };

        context.Pedidos.Add(pedido);
    }
}
    
answered by 14.08.2017 / 16:54
source