Skip to content

What is the best way to remove entities from an untracked child collection #9436

@e-davidson

Description

@e-davidson

What is the best way to remove a child entities from an untracked entity that came from a web application?
If I want to avoid fetching the missing children just for the sake of removing them, I'd need to write the sql manually.

string sql = $@"Delete from {tableName}   where Id not in ({String.Join(",",parent.children.select(child=> child.Id)) })   and {foreignKeyColumn} = {parent.Id} ";
await _context.Database.ExecuteSqlCommandAsync(sql); 

The issue with that method is
A. Now I need an extra call to the database.
B. Its no longer a transaction when I call SaveChanges(). I now must use _context.Database.BeginTransaction().
C. I'm not getting any help generating the sql.

Proposals.

Have an Context.Entry(parent).UpdateCollection(e=> e.child) method.
That will update and remove the missing child items on SaveChanges().

Or

Add a DbSet RemoveRange Overloaded method DbSet.RemoveRange(Expression<Func<T,bool>> predicate ) that can be compiled to sql and run on the server side. So you can do

myDbSet.RemoveRange(e=> e.ParentId == Id && !e.Parent.Children.Select(c=> c.Id).Contains(e.Id) )

This way I don't have to write sql and I'm avoiding an unnecessary call to the database.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions