C# 删除未附加的多对多自引用关系
删除具有自引用关系的独立实体的最佳方法是什么 我的例子很简单,只是一个C# 删除未附加的多对多自引用关系,c#,entity-framework,entity-framework-6,C#,Entity Framework,Entity Framework 6,删除具有自引用关系的独立实体的最佳方法是什么 我的例子很简单,只是一个人物类,它有一个好友列表属性: 编辑:我没有定义额外的关系对象,但我强制实体框架使用额外的表: 我想如何删除老吉米男孩: SqlException#1: SqlException#2: DELETE语句与引用约束“FK_dbo.Friendships_dbo.People_To_PeopleId”冲突。 冲突发生在数据库“FriendsDb”、表“dbo.Friendships”、列“To_PeopleId”中。 我知道发生S
人物
类,它有一个好友列表
属性:编辑:我没有定义额外的关系对象,但我强制实体框架使用额外的表: 我想如何删除老吉米男孩: SqlException#1: SqlException#2: DELETE语句与引用约束“FK_dbo.Friendships_dbo.People_To_PeopleId”冲突。 冲突发生在数据库“FriendsDb”、表“dbo.Friendships”、列“To_PeopleId”中。
我知道发生
SqlException
的原因(SQL Server无法提供级联删除功能,允许同时删除指向老Jimmy boy的所有关系)。所以我的问题是:我怎么能在实体框架的帮助下轻松做到这一点呢?轻松地像删除From PeopleId=3或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();
}
你是在这段时间还是之前试图删除关系的?@Daniel不,我没有。我仍然希望我不会被迫这么做。我没有一个明确的实体来处理多对多的关系。没有
友谊
POCO。在DbContext
中没有DbSet-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();
}
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Friendships_dbo.People_From_PeopleId".
The conflict occurred in database "FriendsDb", table "dbo.Friendships", column '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();
}
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Friendships_dbo.People_To_PeopleId".
The conflict occurred in database "FriendsDb", table "dbo.Friendships", column 'To_PeopleId'.
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();
}