代码之家  ›  专栏  ›  技术社区  ›  Ciaran Gallagher

删除一个或零对一实体与EntityFramework之间的关联

  •  1
  • Ciaran Gallagher  · 技术社区  · 6 年前

    我已经设置了如下内容:

    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;
    

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

    public int? MyOtherThingId{ get; set; }
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   Community CDub    5 年前

    我尝试了以下方法:

    myThing.MyOtherThing = null;
    

    如果要删除可选的 依靠的 实体(此处: MyOtherThing 最重要的 MyThing )通过将其设置为 null ,则必须从包含从属实体的数据库中提取实体,例如:

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

    肌肉疗法

    Include , myThing.MyOtherThing 已经是 无效的 myThing.MyOtherThing = null; 不执行延迟加载,这有点混乱,因为集合的行为不同。

    顺便说一句,依赖实体也可以直接从数据库中删除,这样效率更高。

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