简体   繁体   English

从父实体中删除子实体-EF Core 2.2

[英]Removing child entity from parent entity - EF Core 2.2

I would like to remove an item from collection which exist in one entity. 我想从一个实体中存在的集合中删除一个项目。 The problem I face is: 我面临的问题是:

-entity is being removed from context -实体已从上下文中删除

-after save changes the entity still exists -保存更改后,实体仍然存在

The Parent object: 父对象:

public class MyObject
{
    public int Id { get; private set; }
    public ICollection<ChildObject> ChildObjcets { get; private set; }

    public void RemoveChildObject(ChildObject @object)
    {
        this.ChildObjcets.Remove(@object);
    }
}

the Child object: 子对象:

 public class ChildObject
 {
    public int Id { get; private set; }

    public MyObject MyObject { get; set; }
    public int MyObjectId { get; set; }
}

What I have tried: 我试过的

public void Proceed()
{
     //myObject contain 4 child objects inside
     var myObject = _repo.GetMyObject();
     var childObject = _repo.GetChildObject();

     myObject.RemoveChildObject(childObject);
    //myObject contain 3 items now

} }

Before saving the changes I do not see removed entity in the change tracker - the state should be Removed? 在保存更改之前,我在更改跟踪器中看不到已删除的实体-应该删除状态吗?

var childObjects = ChangeTracker.Entries().Where(x => x.Entity is ChildObject).ToList(); // returns 3 - the removed one does not exist

However when I save changes then the root object still contain 4 entities - so the child object was not removed at all 但是,当我保存更改时,根对象仍然包含4个实体-因此子对象根本没有被删除

_repo.SaveChanges();       
var myObject = _repo.GetMyObject();

Any idea how to handle removing child object from root entity? 任何想法如何处理从根实体删除子对象?

在Entity Framework 6中,执行此操作的更快方法是

context.Children.RemoveRange(parent.Children)

Removing the ChildObject from ChildObjcets (also, note the typo) collection means removing the relation rather than removing the entity from DbContext . 卸下ChildObjectChildObjcets (另外,还要注意错别字)收集方法去除的关系,而不是去除实体DbContext To completely remove the entity you need to explicitly call Remove on the DbSet<ChildObject> which you cannot do directly from your root object. 要完全删除实体,您需要在DbSet<ChildObject>上显式调用Remove ,您不能直接从根对象执行此操作。

I suggest moving this operation to your _repo whatever it actually references to. 我建议将其实际引用的位置移至_repo It should have access to DbContext hence any DbSet<> . 它应该可以访问DbContext因此可以访问任何DbSet<>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM