0

To say I had proxy class and Lazyloading both disabled. and I two objects with a many to many relation. When coming to delete a record, I had the codes:

public void DeleteUser(List<int> ids)
{
    using (var dbContext = new AccountDbContext())
    {
        dbContext.Users.Include("Roles").Where(u => ids.Contains(u.ID)).ToList().ForEach(a => { 
            //a.Roles.Clear(); 
            //dbContext.Users.Remove(a); 
            dbContext.Delete(a);
        });
        dbContext.SaveChanges();
    }
}

It looks like dbContext.Delete(user) will delete the Roles related to the user[which in the database a many to many record is deleted ]. As I thought cascade delete is enabled. So can I say user.Roles.Clear(); is totally unnecessary here? And when should I implement a Clear method?

baozi
  • 679
  • 10
  • 30
  • Take a look at this `Clear` remove reference it doesn't delete the objects http://stackoverflow.com/a/3875502/1876572 – Eldho Oct 26 '15 at 05:10
  • 1
    If cascade delete is enabled on the FK relationship in DB, then calling Clear() is not necessary, since the clearing is done on the DB level. – Martin Staufcik Oct 26 '15 at 05:10

0 Answers0