Entity framework 删除一个或零对一实体与EntityFramework之间的关联
我已经设置了如下内容:Entity framework 删除一个或零对一实体与EntityFramework之间的关联,entity-framework,Entity Framework,我已经设置了如下内容: public class MyThing { public int Id { get; set; } public virtual MyOtherThing { get;set; } } public class MyOtherThing { public int Id { get; set; } public virtual MyThing MyThing { get; set; } } 我的意图是“神话”可以有一个或没有MyOthe
public class MyThing
{
public int Id { get; set; }
public virtual MyOtherThing { get;set; }
}
public class MyOtherThing
{
public int Id { get; set; }
public virtual MyThing MyThing { get; set; }
}
我的意图是“神话”可以有一个或没有MyOtherThing,我还希望有一个从MyOtherThing到它的父对象的导航链接
我已为“MyOtherThing”实体配置了以下EntityBaseConfiguration:
this.HasOptional(x => x.MyThing)
.WithOptionalPrincipal(x => x.MyOtherThing);
我可以将MyOtherThing分配和修改为MyThing没有问题,但是当我想从MyThing中取消分配MyOtherThing时,我该怎么做
我尝试了以下方法:
myThing.MyOtherThing = null;
然后通过设置EntityState.Modified状态编辑实体,但这不会删除实体之间的关联
我尝试将以下内容添加到我的虚构实体中,但这导致更新数据库模型时出现EF“多重性无效”错误:
public int? MyOtherThingId{ get; set; }
提前谢谢
我尝试了以下方法:
myThing.MyOtherThing=null;
如果要通过将其设置为null
,从主体实体(此处MyOtherThing
)中删除可选的从属实体(此处:MyOtherThing
),则必须从包含从属实体的数据库中提取该实体,例如:
var mything=context.MyThings.Include(m=>m.MyOtherThing)
.Single(t=>t.Id==idValue);
(稍后将所属的MyOtherThing
加载到上下文中时也可以,例如通过延迟加载)
如果没有Include
,MyOtherThing
已为null
,EF未检测到任何更改。注意语句myThing.MyOtherThing=null代码>不执行延迟加载,这有点令人困惑,因为集合的行为不同
顺便说一句,依赖实体也可以直接从数据库中删除,这样效率更高
var ot=context.Set().Find(idValue);
context.Set().Remove(ot);
SaveChanges();
请说明哪一个是主体实体,哪一个是从属实体?我已经用我使用的EntityBaseConfiguration更新了这个问题—“MyOtherThing”是我认为的主体实体—这是一个具有导航属性的问题。这是一个虚构的实体,我想在这里实际存储相关的MyOtherThing ID。这里阅读我的答案!希望它能对您有所帮助:您应该从数据库中获取MyThing
,并Include()
MyOtherThing
。然后将其设置为null将生效。@CiaranGallagherInclude
适用于集合和引用导航属性。当实体没有明确的FK时,不加载引用导航属性(通过Include
或lazy,例如\uuu=myThing.MyOtherThing;
),它是null
,因此将其设置为null
无效。