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.
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.
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
This way I don't have to write sql and I'm avoiding an unnecessary call to the database.