Entity Framework update entity and childs entities, Bulk Delete part 2

In the previous post I’ve explained how to perform a single update, but what I’ve to do If I need to update a master entity and related child?
As I’ve explained to update my model I use the 3rd method:
Attach the model and set EntityState.Modified
Now how can I update the child in a many to many relationship?
Usually I delete old children and then I reinsert the new ones.
To do this in EF I need the bulk delete but EF6 currently don’t support it!!!!
The only way available in EF6 without use ExecuteSQlCommand is DbSet.RemoveRange.
Unfortunately RemoveRange will perform a select on DB also without .ToList() call but it’s faster than delete each item loaded by the first query

The code above will work also in one to one relationship.

public void UpdateSymbol(Symbol model, IEnumerable<SymbolExtra> extra = null)
{
    // I attach the main entity without perform a select
    this.Trading_Symbols.Attach(model);

    #region remove all associated extra, this works also with one to one relationship and not only with one to many relationship
    var qDelete = from a in this.SymbolExtras
    where a.IdSymbol == model.IdSymbol
    select a;
    // RemoveRange unfortunately will execute the select on DB!!! But EF6 don't currently support bulk remove or bulk update
    this.SymbolExtras.RemoveRange(qDelete);

    // If extra is not null I'll add the new children
    model.SymbolExtras = extra;
    
    // I sign the model modifyed
    this.Entry(model).State = EntityState.Modified;
}

Sample usage

{
    MyDAL.UpdateSymbol(m, e);
    MyDAL.SaveChanges();
}
Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in c#, Entity Framework e contrassegnata con , , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...