Insert Multiple Entity Framework Items

1

I have the following method to add customer 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();
    }
}

It works without problems, but when I save a client I added two new phones with 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 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 insert the phones the field of the primary key of them is "0", but how to solve it?

    
asked by anonymous 13.01.2016 / 17:51

1 answer

0

Could you change the primary key field? For example, use an identity to generate auto increment in the key.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int32 Id { get; set; }
    
13.01.2016 / 18:42