删除未附加的多对多自引用关系
本文关键字:关系 自引用 删除 | 更新日期: 2023-09-27 18:35:38
删除具有自引用关系的未附加实体的最佳方法是什么?
我的例子很简单,只是一个具有List<People> Friends
属性的People
类:
编辑 :我没有定义额外的关系对象,但我强制实体框架使用额外的表:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<People>()
.HasMany(people => people.Friends)
.WithMany()
.Map(configuration =>
{
configuration
.MapLeftKey("From_PeopleId")
.MapRightKey("To_PeopleId")
.ToTable("Friendships");
});
}
架构:
Id Name
== ======
1 Martha
2 Martin
3 Jim
From_PeopleId To_PeopleId
============= ===========
1 2
1 3
3 2
以及我想如何删除老吉米男孩:
using (var context = new FriendsDbContext())
{
var people = context.Peoples.Find(3);
context.Peoples.Remove(people);
context.SaveChanges();
}
SqlException #1:
DELETE 语句与 REFERENCE 约束"FK_dbo.Friendships_dbo。People_From_PeopleId"。冲突发生在数据库"FriendsDb",表"dbo。友谊","From_PeopleId"栏。我摆脱老
吉米男孩的第二种方法,包括他的亲戚:
using (var context = new FriendsDbContext())
{
var people = context.Peoples
.Include(p=>p.Friends)
.Single(p=>p.Id==3);
context.Peoples.Remove(people);
context.SaveChanges();
}
SqlException #2:
DELETE 语句与 REFERENCE 约束"FK_dbo.Friendships_dbo。People_To_PeopleId"。冲突发生在数据库"FriendsDb",表"dbo。友谊","To_PeopleId"栏。
我知道为什么会发生SqlException
(SQL Server无法提供级联删除,允许立即删除指向老吉米男孩的所有关系)。所以我的问题是:如何在实体框架的帮助下轻松做到这一点?很容易喜欢DELETE Friendships WHERE From_PeopleId=3 OR To_PeopleId=3
.
尝试删除之前或同时
的关系using (var context = new FriendsDbContext())
{
var friendships = context.Friendships.Where(x => x.From_PeopleId == 3 || x.To_PeopleId == 3).ToList();
context.RemoveRange(friendships);
var people = context.Peoples.Find(3);
context.Peoples.Remove(people);
context.SaveChanges();
}