EF关系(1到0..1)将不会被删除

时间:2016-08-08 12:07:53

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

我在Entity Framework V6.1.1中有一个Code First模型,基本上看起来像这样:

public class TinMan {
    public int Id { get; set; }
    public virtual Heart Heart { get; set; }
}

public class Heart {
    public int Id { get; set; }
}

这在这样的实际数据库中表示,其中Heart_Id列由EF自动生成,这也创建了两个表之间的外键关系:

TinMen:                 Hearts:

Id    Heart_Id          Id
1     1                 1
2     3                 2
3     NULL              3

创建一个不存在的关系,或者更改现有关系的工作正常:

using (MyDbContext dbContext = new MyDbContext()) {
    TinMan bill = dbContext.TinMen.FirstOrDefault(man => man.Id == 1);
    if (bill != null) bill.Heart = 2;
    TinMan bob = dbContext.TinMen.FirstOrDefault(man => man.Id == 3);
    if (bob != null) bob.Heart = 1;
    dbContext.SaveChanges();
}

现在我尝试删除关系:

using (MyDbContext dbContext = new MyDbContext()) {
    TinMan jebediah = dbContext.TinMen.FirstOrDefault(man => man.Id == 2);
    if (jebediah != null) jebediah.Heart = null;
    dbContext.SaveChanges();
}

执行此操作后,具有ID == 2 仍然的TinMan在数据库中有一个Heart,即在数据库中 设置为NULL

为什么?

1 个答案:

答案 0 :(得分:2)

试试这个:

using (MyDbContext dbContext = new MyDbContext())
{
    TinMan jebediah = dbContext.TinMen.FirstOrDefault(man => man.Id == 2);
    context.Entry(jebediah).Reference(t => t.Heart).CurrentValue = null;
    dbContext.SaveChanges();
}

根据我的评论,这是另一种方法:

using (MyDbContext dbContext = new MyDbContext())
{
    TinMan jebediah = dbContext.TinMen.FirstOrDefault(man => man.Id == 2);
    context.Entry(jebediah).Reference(t => t.Heart).Load();
    jebediah.Heart = null;
    dbContext.SaveChanges();
}

在任何情况下,这都是具有显式外键属性(例如public int? HeartId { get; set; })可能有利的情况。使用外键属性,您可以在不预先加载相关实体的情况下删除关系。例如:

using (MyDbContext dbContext = new MyDbContext())
{
    TinMan jebediah = dbContext.TinMen.FirstOrDefault(man => man.Id == 2);
    jebediah.HeartId = null;
    dbContext.SaveChanges();
}
相关问题