C# EF关系(1对0..1)赢得';不能删除
我在Entity Framework 6.1.1版中有一个代码优先模型,基本上如下所示:C# EF关系(1对0..1)赢得';不能删除,c#,.net,entity-framework,entity-framework-6,C#,.net,Entity Framework,Entity Framework 6,我在Entity Framework 6.1.1版中有一个代码优先模型,基本上如下所示: public class TinMan { public int Id { get; set; } public virtual Heart Heart { get; set; } } public class Heart { public int Id { get; set; } } 这在这样的实际数据库中表示,其中Heart\u Id列由EF自动生成,EF还创建了两个表之间的
public class TinMan {
public int Id { get; set; }
public virtual Heart Heart { get; set; }
}
public class Heart {
public int Id { get; set; }
}
这在这样的实际数据库中表示,其中Heart\u Id
列由EF自动生成,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在数据库中仍有心脏,即,它在数据库中被设置为NULL
为什么?试试这个:
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();
}
这并不能解释为什么将导航属性设置为<代码> null <代码>不起作用,但是请注意,如果没有额外的配置,EF将考虑<代码>从<代码>心脏到
null
不起作用?当您从数据库加载TinMan
实体时,相关的心脏
尚未加载,因为已启用延迟加载。因此,当您将其设置为null
时,就EF而言,实际上没有发生任何事情。设置相关的H如果事先加载了eart
tonull
,它将起作用。我更新了我的答案(包括一个示例)。