Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Delete All on Submit

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?

like image 864
Shawn Mclean Avatar asked Jan 09 '11 19:01

Shawn Mclean


3 Answers

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();
like image 193
Femaref Avatar answered Dec 10 '22 15:12

Femaref


@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);
}
like image 32
Stephen Swensen Avatar answered Dec 10 '22 16:12

Stephen Swensen


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

of course, this solution can work. But, it is the most inefficient solution. This solution will generate one delete SQL command for each record (entity). Imaging that you want to delete all data before year 2000 . there are more than 1,000,000 records in the database. If delete these objects in this way, more than 1,000,000 SQL commands will be sent to the server, it is a unnecessary big waste. What

like image 30
Jerry Avatar answered Dec 10 '22 17:12

Jerry