Entity Framework DataContext enforces delete cascade even if it’s disabled
I have 2 tables with a many to many relation (Users <-> Permissions):
modelBuilder.Entity<User>().HasMany(x => x.Permission).WithMany()
I disabled “delete cascade” from the many to many relation to get an exception if the permission is referenced by a user.
The database schema is generated correctly. When I delete a permission (item) like following:
_dbContext.Entry(item).State = EntityState.Deleted; _dbContext.SaveChanges();
the relation gets removed and no validation exception is fired. However, when I delete the permission with pure SQL from the SQL Server Management Studio:
DELETE FROM [Permissions] WHERE Id = 3
the exception is fired.
Note: I load all entities eager.
Has anyone an idea why the Entity Framework fires no exception and allows this operation?
Problem found: If I load the data lazy the deletion work as expected. Exception is fired:
(The DELETE statement conflicted with the REFERENCE constraint....)