Skip to content

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

Closed as duplicate

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.

Activity

  1. ajcvickers commented on Aug 17, 2017

    @ajcvickers
    Contributor

    @e-davidson This issue and the ideas you propose are being tracked by #5536 (better support for disconnected entities) and #795 (set-based updates). Closing this as a duplicate of those issues.

  2. jzabroski commented on Jul 5, 2018

    @jzabroski

    @ajcvickers oy vey.... I think you should close #5536 and create a new ticket with clear scenarios. How is anyone supposed to contribute to such unwieldy tickets?

    Here is one possible ticket:

    Note, this wouldn't solve any problems, just call out unaddressed gaps in the API which can catch people by surprise, as well as educate Microsoft on clear product gaps, by looking at features as Orthogonal Arrays of pairwise feature interactions.

  3. jzabroski commented on Jul 5, 2018

    @jzabroski

    I created a pull request to start refactoring the documentation, so it will be clearer which scenarios result in run time exceptions, here: dotnet/EntityFramework.Docs#810

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions