Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
e-davidson opened this issue Aug 16, 2017 · 3 comments
Closed

Comments

@e-davidson
Copy link

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.

@ajcvickers
Copy link
Member

@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.

@jzabroski
Copy link

jzabroski commented Jul 5, 2018

@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.

@jzabroski
Copy link

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

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants