EF 4.1 Database First approach.
Say I have this table schema
Users 1—M UserRoles M—1 Roles
Cascade delete is setup in the Foreign Keys
The UserRoles table has additional columns like CreatedDate so I create a model for UserRoles and map accordingly.
I end up with the following Models:
User
----
int Id
string Name
List<UserRoles> UserRoles
UserRoles
---------
int UserId
int RoleId
DateTime CreatedDate
User User
Role Role
Role
----
int Id
string Name
List<UserRoles> UserRoles
If I have my configuration correct, should I be able to delete a user and will the user roles rows be deleted WITHOUT having to clear the UserRoles collection manually?
So can I just do this:
DbContext.Entry(user).State = EntityState.Deleted;
DbContext.SaveChanges();
Or do I HAVE to do this:
user.UserRoles.Clear();
DbContext.Entry(user).State = EntityState.Deleted;
DbContext.SaveChanges();
My testing shows I HAVE to clear the child collection, but I find conflicting information that if I have cascade delete setup correctly it should work by only deleting the User.
When I DON’T clear the UserRoles I receive this error:
The relationship could not be changed because one or more of the
foreign-key properties is non-nullable
Thanks for you help in clarifying this!
You must use
It is not the same thing as setting the state to
Deleted. Setting the state won’t mark any child objects with cascading delete setup asDeletedbutRemovewill do.Setting the state to
Deletedshould work IF no children are loaded into the context because EF will send only a DELETE statement for the parent to the database and the database will delete the children as well due to the cascading delete in the database.IF however you have loaded children into the context setting the state on the parent to
Deletedwon’t set the state of the children. EF will throw the exception, it’s not the database who complains.