Insert multiple Entity Framework items

Asked

Viewed 94 times

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

  • I saw but didn’t understand.

1 answer

0

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

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int32 Id { get; set; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.