Updating collections with entity framework

4

Is it possible to update the Collection of an entity with relationship one-to-many through its 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 foo.Bars objects to the table, without removing the records that do not exist in the collection. The workaround I found was to dbSet.RemoveRange of objects not in foo.Bars to delete them from the database.

What is the most appropriate way to update a collection?

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

Looking at this Daniel post Simmons , it seems that the 6.x of entity framework version does not support this feature. The behavior done by ORM is to modify the value of the foreign keys to null , not deleting the registry.

Is there a recommended approach to perform this operation?

    
asked by anonymous 23.09.2015 / 14:25

1 answer

5

To this day I have not found an answer that explained this properly, so I've created an algorithm that I use for these cases. Assume a Cliente entity that has N% with% s, and that this is part of an edit in 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();
    }
}
    
23.09.2015 / 16:31