Reputation: 2195
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?
Upvotes: 2
Views: 4907
Reputation: 1495
use .WillCascadeOnDelete(true) or Include
WillCascadeOnDelete:
modelBuilder.Entity<Parent>()
.HasMany<Child>(c => c.Children)
.WithOptional(x => x.Parent)
.WillCascadeOnDelete(true);
use Include
var adv = db.Adv.Include(b => b.Features)
.Include(b => b.AdvDetails)
.Include(b => b.AdvGallery)
.FirstOrDefault(b => b.Id == id);
db.Adv.Remove(adv);
for .HasMany(...).WithMany(...) Include is ok
Upvotes: 0
Reputation: 156
Use Cascade Delete option
Cascade delete allows dependent data to be automatically deleted when the principal record is deleted. If you delete a Destination, for example, the related Lodgings will also be deleted automatically. Entity Framework supports cascade delete behavior
for in-memory data as well as in the database. it is recommended that you implement cascade delete on entities in the model if their mapped database objects also have cascade delete defined.
Database First Approach
Cascade delete defined in a database constraint as,
Code First Approach
HasRequired(l=>l.OwnedGroups).WithMany(d=>d.Groups)
.WillCascadeOnDelete(true)
HasRequired(l=>l.Groups).WithMany(d=>d.Users)
.WillCascadeOnDelete(true)
Upvotes: 1
Reputation: 10705
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()
Upvotes: 4
Reputation: 743
You must apply ON DELETE CASCADE
, to let the system delete the related data.
Upvotes: 0