Remove Entity Framework Submit it all!

entity-framework

Question

What I could accomplish using LINQ to SQL is:

context.User_Roles.DeleteAllOnSubmit(context.User_Roles.Where(ur => ur.UserId == user.UserId));

What does this look like in entity framework?

1
18
1/9/2011 7:30:36 PM

Accepted Answer

The notion from @Femaref is sound, however for a genuine analog to L2E'sDeleteAllOnSubmit to prevent "collection updated during enumerating" issues, you'll want your extension method to create a duplicate of the entities being destroyed before enumerating.

public static void DeleteAllObjects<TEntity>(this ObjectSet<TEntity> set, IEnumerable<TEntity> data) where TEntity : class {
    foreach(var entity in data.ToList()) //data.ToList() makes a copy of data for safe enumeration
        set.DeleteObject(entity);
}
5
2/9/2014 5:49:11 PM

Popular Answer

foreach(var entity in context.User_Roles.Where(ur => ur.UserId == user.UserId))
{
  context.User_Roles.DeleteObject(entity);
}
context.SaveChanges();

Naturally, you could create an extension method that would include this.

This might resemble the following:

public static void DeleteObjects<TEntity> (this ObjectSet<TEntity> set, IEnumerable<TEntity> data) where TEntity : class
{
  foreach(var entity in data)
    set.DeleteObject(entity);
}

as called:

context.User_Roles.DeleteObjects(context.User_Roles.Where(ur => ur.UserId == user.UserId))
context.SaveChanges();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow