Remove Entity Framework Submit it all!

entity-framework

Question

In LINQ to SQL, I could do:

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

Whats the equivalent to this for entity framework?

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

Accepted Answer

@Femaref has the right idea, but for a true analog to L2E's DeleteAllOnSubmit, you'll want your extension method to make a copy of the entities being deleted before enumerating so that you don't get "collection modified while enumerating" exceptions.

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();

Of course, you can write an extension method, which would encapsulate this.

This would be something like this:

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

Called like:

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