Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EF关系(1对0..1)赢得';不能删除_C#_.net_Entity Framework_Entity Framework 6 - Fatal编程技术网

C# EF关系(1对0..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还创建了两个表之间的

我在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还创建了两个表之间的外键关系:

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将考虑<代码>从<代码>心脏到 Timman 的一对多< <代码>关系。这是我在您回答时看到的。我试过了,它工作了。知道为什么吗?仅将属性设置为
null
不起作用?当您从数据库加载
TinMan
实体时,相关的
心脏
尚未加载,因为已启用延迟加载。因此,当您将其设置为
null
时,就EF而言,实际上没有发生任何事情。设置相关的
H如果事先加载了eart
to
null
,它将起作用。我更新了我的答案(包括一个示例)。