fonix232 fonix232 - 1 year ago 100
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 = null;

Is there something I'm missing here?

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download