删除未附加的多对多自引用关系

时间:2016-02-22 14:48:19

标签: c# entity-framework entity-framework-6

删除具有自引用关系的未附加实体的最佳方法是什么?

我的示例很简单,只有一个People类,其List<People> Friends属性:

编辑 :我没有定义额外的关系对象,但我强制Entity Framework使用额外的表:

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:

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();
}

SqlException#2:

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'.

我知道为什么SqlException发生了(SQL Server无法提供级联删除,允许删除指向旧Jimmy男孩的所有关系)。所以我的问题是:我怎样才能在Entity Framework的帮助下轻松实现?很容易就像DELETE Friendships WHERE From_PeopleId=3 OR To_PeopleId=3

1 个答案:

答案 0 :(得分:2)

尝试在此期间或同时删除关系

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();
}