1
I have the following method to add doclient data
public void Alterar(CLIENTE Cliente)
{
using (Entity.DominioEntity db = new Entity.DominioEntity())
{
//Alterar/Adicionar Telefone
foreach (var item in Cliente.TELEFONE)
{
if (item.Codigo == 0)
db.Entry(item).State = EntityState.Added;
else
db.Entry(item).State = EntityState.Modified;
}
//Deletar Telefones
List<int> delItemTelefone = new List<int>();
foreach (var item in Cliente.TELEFONE)
{
///Se o codigo = zero e Deletar = true -> não faz nada.
if (item.Deletar == true)
delItemTelefone.Add(item.Codigo);
}
foreach (var item in delItemTelefone)
{
db.Entry(cliente.TELEFONE.Single(t => t.Codigo == item)).State = EntityState.Deleted;
}
db.CLIENTE.Attach(Cliente);
db.Entry(Cliente).State = EntityState.Modified;
db.SaveChanges();
}
}
Works smoothly but when I go to save a customer I added two new phones the following error:
Attaching an Entity of type 'Dominio.Entity.TELEFONE' 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.
I know the problem is that when I input the phones their primary key grave is "0," but how to fix it?
Have you seen this? http://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
– Jhonathan
I saw but didn’t understand.
– Gabriel Santos Reis