Updating collections with Entity framework

Asked

Viewed 235 times

4

It is possible to update the Collection of an entity with one-to-many through his navigation property?

public class Foo
{
  public virtual IList<Bar> Bars {get; set;}

  public int FooID { get; set; }
}


public void UpdateFoo(Foo foo)
{
  dbContext.Set<Foo>.Attach(foo);
  dbContext.Entry(foo).State = EntityState.Modified;
}

The behavior of EF is to add the objects of foo.Bars table, without removing records that do not exist in the collection. The alternative solution I found was to perform a dbSet.RemoveRange objects not existing in foo.Bars to delete them from the database.

What is the most appropriate way to update a Collection?

EDIT-----------------

Analyzing this post by Daniel Simmons, looks like the version 6.x of entity framework does not support this resource. The behavior performed by ORM is to modify the value of foreign keys to null, not deleting the record.

Is there any recommended approach to perform this operation?

1 answer

5


Until today I have not found an answer that would explain me this properly, so I created an algorithm that I use for these cases. Suppose an entity Cliente that has N ClienteTelefones, and that this is part of an edition on an ASP.NET MVC system:

// Telefones Originais
var telefonesOriginais = db.ClienteTelefones.AsNoTracking().Where(ct => ct.ClienteId == cliente.ClienteId).ToList();

if (cliente.ClienteTelefones != null)
{
    // Telefones Excluídos
    foreach (var telefoneOriginal in telefonesOriginais)
    {
        if (!cliente.ClienteTelefones.Any(ct => ct.ClienteId == telefoneOriginal.ClienteId))
        {
            var telefoneExcluido = db.ClienteTelefones.Single(ct => ct.ClienteTelefoneId == telefoneOriginal.ClienteId);
            db.ClienteTelefones.Remove(telefoneExcluido);
            await db.SaveChangesAsync();
        }
    }

    // Telefones Inseridos ou Alterados
    foreach (var telefone in cliente.ClienteTelefones)
    {
        if (!telefonesOriginais.Any(ct => ct.ClienteId == telefone.ClienteId))
        {
            // Telefone não existe ainda. Inserir.
            telefone.ClienteId = cliente.ClienteId;
            db.ClienteTelefones.Add(telefone);
        }
        else
        {
            // Telefone já existe. Marcar como alterado.
            db.Entry(telefone).State = EntityState.Modified;
        }

        await db.SaveChangesAsync();
    }
}
  • 1

    Here always gives this Exception when mark as modified: Saving or Accepting changes failed because more than one Entity of type '' have the same Primary key value. Ensure that explicitly set Primary key values are Unique. Ensure that database-generated Primary Keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First Configuration. Use the 'Hasdatabasegeneratedoption" Fluent API or 'Databasegeneratedattribute' for Code First Configuration. Any idea of what?

  • 1

    I managed to fix it. It was a sum of wrong things. Anyway your answer saved my skin, thank you very much!

Browser other questions tagged

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