Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Problema many-to-many

No quinto exercício do capitulo sete, foi sugerido o uso do Attach(), para resolver o problema que quando se salva a venda ele duplica os produtos. Pois bem eu apliquei a solução sugerida e passei a ter o seguinte erro: Attaching an entity of type 'LojaWebEF.Entidades.Produto' 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.

Este é o código do meu método Adicionar:

public void Adiciona(Venda venda)
{
      foreach (Produto produto in venda.Produtos)
      {
           this.contexto.Produtos.Attach(produto);
      }
      this.contexto.Vendas.Add(venda);
}

Alguém teria uma sugestão de como corrigir este problema?

1 resposta
solução!

Fiz um novo teste e tive sucesso. Sinceramente não fiz nenhuma alteração mas passou a funcionar.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software