我有两个关系表:
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.
我想要从用户访问订阅。
答案 0 :(得分:1)
删除订阅时,必须确保将具有该订阅的所有用户的订阅引用设置为null,否则会违反数据库中的外键约束。我认为,将订阅删除的用户加载到上下文中就足够了。 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();
}