【发布时间】:2016-08-08 12:07:52
【问题描述】:
我在实体框架 6.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。
为什么?
【问题讨论】:
-
这并没有解释为什么将导航属性设置为
null不起作用,但请注意,如果没有额外的配置,EF 将考虑one-to-many关系从Heart到TinMan.
标签: c# .net entity-framework entity-framework-6