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?
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();
@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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With