fonix232 fonix232 - 3 months ago 26
ASP.NET (C#) Question

Deleting a many-to-many relationship object in Entity Framework

I have a web server where I serve User objects through a REST API.

Recently I've added the option for users to create Groups. Groups have a Name, a Color (represented as an int), an Owner (User object reference), and Members.

The Members property is a many-to-many relationship. One User can be member of multiple Groups, and one Group may have multiple members.

However I'm having problems with the removal of Groups. I want to give the Owner user the option to delete a Group - thus, removing all members, and removing the reference to the Group itself.

However I'm getting the following error upon trying to delete it:

The DELETE statement conflicted with the REFERENCE constraint \"FK_GroupUser_Group\". The conflict occurred in database \"database\", table \"dbo.GroupUser\", column 'Groups_Id'.\r\nThe statement has been terminated.


I'm using the following code to remove the Group:

using (var db = new DBContext())
{
group.Owner.OwnedGroups.Remove(group);
group.Owner = null;
db.Groups.Remove(group);
db.SaveChanges();
}


Is there something I'm missing here?

Answer

The message says you have a conflict with the REFERENCE constraint FK_GroupUser_Group. It seems the group still have users, though the group does not have an owner anymore (since you deleted it). Try clearing the users association:

group.Users.Clear()‌​