'How to modify / delete owned object from entity in EF core 6

I'm building an Asp.Net core Api project. I have a Parent entity as Aggregate root. That parent entity has a collection of Owned types. If instead of collection of Owned types I have collection of Entities, I would simply tell the parent to delete the entity by it's Id like this:

// Parent entity method
public void DeleteChild(int childId)
{
   var existing = this._children.FirstOrDefault(x=>x.Id == childId);
   ...
   this._children.Remove(existing);
}

How to delete the owned object in the collection of an aggregate (owned entity does not have an Id property)?

//Parent entity method
public void DeleteChild(?????????) //Don't know what to put here, a surrogate key?
{
    ...
}

The same goes for modifying the Owned object. What is the best practice for this?

Thanks

P.S. I'm using EF Core 6.x



Solution 1:[1]

You need to reference the value-object by itself:

public void DeleteChild(Child child)
{
    // redacted
}

Solution 2:[2]

You just have to find the parent first. Then you can iterate through the childrens and delete the ones that you want. Then just call the save changes and they should be removed.

Example:

// Parent entity method
public void DeleteChild(int childId, idParent)
{
   var existing = dbcontext.FirstOrDefault(x=>x.Id == idparent);
   
   for (int i = 0; i < collention.length; i++)
   {
       if (collection[i].id = childId)
          collection[i] = null;
   }

   dbcontext.SaveChangesAsync();

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ArwynFr
Solution 2 srzsanti