Removing child entity from parent entity - EF Core 2.2

asp.net-core c# entity-framework-core

Question

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

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

Any idea how to handle removing child object from root entity?

1
0
12/19/2018 11:58:57 AM

Popular Answer

In Entity Framework 6 a faster way to do the operation is

context.Children.RemoveRange(parent.Children)
1
12/19/2018 12:03:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow