1

我有两个有关系的表:

    modelBuilder.Entity<User>()
        .HasOptional(u => u.Subscription)
        .WithMany();

我怎样才能删除关系?我想删除订阅但保留所有用户。如果我删除订阅 EF 抛出异常:

"The DELETE statement conflicted with the REFERENCE constraint
\"FK_Users_Subscriptions_Subscription_Id\". 
The conflict occurred in database \"db\",table \"dbo.Users\",
column 'Subscription_Id'.\r\nThe statement has been terminated.

我想从用户访问订阅。

4

1 回答 1

1

当您删除订阅时,您必须确保拥有该订阅的所有用户的订阅引用都设置为空,否则您违反了数据库中的外键约束。我认为,将订阅的用户加载到上下文中就足够了。EF 将自动修复关系:

using (var ctx = new MyContext())
{
    var subscriptionToDelete = ctx.Subscriptions.Find(subscriptionToDeleteId);
    ctx.Users.Where(u => u.Subscription.Id == subscriptionToDeleteId).Load();

    ctx.Subscriptions.Remove(subscriptionToDelete);

    ctx.SaveChanges();
}
于 2012-06-23T13:38:46.757 回答