使用EntityFramework

时间:2019-01-09 17:06:05

标签: 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; }
}

我的意图是'MyThing'可以具有MyOtherThing之一,也可以不具有MyOtherThing,并且我还希望从MyOtherThing到其父项的导航链接。

我已经为“ MyOtherThing”实体配置了以下EntityBaseConfiguration:

this.HasOptional(x => x.MyThing)
    .WithOptionalPrincipal(x => x.MyOtherThing);

我可以将MyOtherThing分配和修改为MyThing,但是没有问题,但是当我想从“ MyThing”取消分配“ MyOtherThing”时,该怎么做?

我尝试了以下操作:

myThing.MyOtherThing = null;

,然后通过设置 EntityState.Modified 状态来编辑实体,但这并没有删除实体之间的关联。

我尝试将以下内容添加到MyThing实体中,但这导致在更新数据库模型时出现EF“多重性无效”错误:

public int? MyOtherThingId{ get; set; }

提前谢谢!

1 个答案:

答案 0 :(得分:2)

  

我尝试了以下操作:

myThing.MyOtherThing = null;

如果要通过设置从主要实体(此处为MyOtherThing)中删除可选的 dependent 实体(此处为MyThing)到null,您必须从数据库中拉出包含相关实体的实体,例如:

var mything = context.MyThings.Include(m => m.MyOtherThing)
              .Single(t => t.Id == idValue);

(在以后将所有物MyOtherThing加载到上下文中(例如通过延迟加载)也可以)。

在没有Include的情况下,myThing.MyOtherThing已经是null,并且EF未检测到任何更改。请注意,语句myThing.MyOtherThing = null;不会执行延迟加载,这有点令人困惑,因为对于集合而言,其行为是不同的。

通过这种方式,还可以直接从数据库中删除从属实体,这更加有效。

var ot = context.Set<MyOtherThing>().Find(idValue);
context.Set<MyOtherThing>().Remove(ot);
context.SaveChanges();
相关问题