【问题标题】:How do you delete Child from Parent entities in EF Core?如何从 EF Core 中的父实体中删除子实体?
【发布时间】:2018-06-18 07:38:55
【问题描述】:

我有这些课

public class HomeSection2
{
    public HomeSection2()
    {
        HomeSection2Detail = new List<HomeSection2Detail>();
    }

    public Guid ID { get; set; }
    public string Title { get; set; }
    public string Header { get; set; }

    public virtual List<HomeSection2Detail> HomeSection2Detail { get; set; }
}

public class HomeSection2Detail
{
    public Guid ID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public int? Sequence { get; set; }

    public virtual HomeSection2 HomeSection2 { get; set; }
}

当我打电话时

var obj2detail = obj2.HomeSection2Detail.Where(w => w.ID == detail.ID).FirstOrDefault();
if (obj2detail != null)
{
    obj2.HomeSection2Detail.Remove(obj2detail);
}  

从我的应用程序中,它只会删除关系,但不会删除数据库中的记录。

【问题讨论】:

  • obj2的类型是什么?
  • @MohammedNoureldin: HomeSection2

标签: c# asp.net-mvc entity-framework asp.net-core-mvc ef-core-2.0


【解决方案1】:

您需要从HomeSection2Details DbSet 中显式删除实体。

dbContext.HomeSection2Details.Remove(obj2detail);

【讨论】:

    【解决方案2】:

    无需从DbContext 中显式删除依赖实体;如果一个依赖实体在从其主体实体中删除时应该总是被删除,这可以通过在DbContext 上的配置来实现,使用OnDelete

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder
            .Entity<HomeSection2>()
            .HasMany(x => x.HomeSection2Detail)
            .WithOne(x => x.HomeSection2)
            .OnDelete(DeleteBehavior.Cascade); // Causes dependent entity to be deleted
    }
    

    【讨论】:

      【解决方案3】:

      您需要执行以下操作。在 sn-p 中添加为 cmets 的说明:

      var obj2detail = obj2.HomeSection2Detail.Where(w => w.ID == detail.ID).FirstOrDefault();
      if (obj2detail != null)
      {
          // this line of code only delete the relationship.
          obj2.HomeSection2Detail.Remove(obj2detail);
      
          // If you want to delete the entity you need the DbContext help 
          // and your HomeSection2Details DbSet<HomeSection2Detail> like below
          yourDbContext.HomeSection2Details.Remove(obj2detail);
      }
      

      【讨论】:

        【解决方案4】:

        您直接使用 RemoveRange 或 Remove DbContext

         _db.RemoveRange(obj2detail);
        

        【讨论】:

          猜你喜欢
          • 2022-12-02
          • 2021-12-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-16
          • 2021-07-22
          • 2022-01-20
          • 1970-01-01
          相关资源
          最近更新 更多