Search code examples
c#entity-framework.net-6.0in-memory-database

Error : 'The instance of entity type 'Produtos' cannot be tracked


Hello I'm trying to add a list of products to my order but I'm getting the exception in my C# code: System.InvalidOperationException: 'The instance of entity type 'Products' cannot be tracked because another instance with the key value '{Id: 1} ' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.' I tried some solutions but I couldn't solve the problem.I am using for my test application inMemoryDatabase.

 public class Pedidos
    {
        [Key]
        public int Id { get; set; }
        public string Descricao { get; set; }
        public decimal Valor { get; set; }
        public DateTime DataCriacao { get; set; } = DateTime.Now;
        public List<Produtos> ProdutosPedido { get; set; }
    }

public class Produtos
    {
        public int Id { get; set; }
        public string Descricao { get; set; }

        public int FornecedorId { get; set; }

        public Fornecedores Fornecedores { get; set; }

        public int TributacaoId { get; set; }

        public Tributacoes Tributacoes { get; set; }
    }
 public Pedidos Adicionar(Pedidos pedido)
        {
            _dbContext.Pedido.Add(pedido);
            _dbContext.SaveChanges(); //error here
            return pedido;
        }
 {
    "id": 2,
    "descricao": "Pedido 1",
    "valor": 52.36,
    "dataCriacao": "2023-08-25T08:59:59.4587309-03:00",
    "produtosPedido": [ //class produto
      {
        "id": 1,
        "descricao": "Teste Produto",
        "fornecedorId": 1,
        "tributacaoId": 1,
      }
    ]
  }
public class EFDBContext : DbContext
    {
        public EFDBContext(DbContextOptions<EFDBContext> options) : base(options)
        {

        }
        public DbSet<TipoDespesas> TipoDespesa { get; set; }
        public DbSet<Fornecedores> Fornecedor { get; set; }
        public DbSet<Tributacoes> Tributacao { get; set; }
        public DbSet<Produtos> Produto { get; set; }
        public DbSet<Pedidos> Pedido { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseInMemoryDatabase("BC-Teste");
            optionsBuilder.EnableSensitiveDataLogging();
        }
    }

I already tried to modify the product state.


Solution

  • Then modify your code in this way:

    public Pedidos Adicionar(Pedidos pedido)
    {
        foreach (var produto in pedido.ProdutosPedido)
        {
            _dbContext.Attach(produto);
        }
        _dbContext.Pedido.Entry(pedido).State = EntityState.Modified;
        _dbContext.SaveChanges();
        return pedido;
    }