What is the most effective way to delete entites that satisfy a condition from a database?

本秂侑毒 提交于 2021-01-27 11:23:39

问题


AFAIK, there isn't a direct way to delete entities using a predicate such as

DbSet.RemoveWhere(() => {})

I tried a few ways to delete and don't know which is the most efficient way to do it. Could you point me in the right direction?

The first and most basic thing I tried is:

_context.Users.RemoveRange(_context.Users.Where(u => u.Name.Equals("John")));

which loads the user to the memory before deletion. I don't like this approach. The second way I tried is using the Z.EntityFramework.Plus package:

_context.Users.Where(u => u.Name.Equals("John")).Delete()

which claims to delete objects without loading them but I don't know if this is better then the first way. Also this feels wrong as the efcore should have a proper way to do this. The third attempt I made was something like this:

_context.Users.Where(u => u.Name.Equals("John")).ForEachAsync(u => _context.Users.Remove(u));

I don't know if this loads the users into the memory and it has a nasty Async in there. It also gives the following exception:

"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."

回答1:


I think ExecuteSqlRaw is more appropriate for you:

_context.Database.ExecuteSqlRaw("DELETE FROM Users WHERE Name = @p0", "John");

Generally Remove and RemoveRange are suitable for situations which you already have Primary Key (usually Id) of objects, in those cases you can do something like this:

_context.Users.Remove(new User {Id = id});


来源:https://stackoverflow.com/questions/62307139/what-is-the-most-effective-way-to-delete-entites-that-satisfy-a-condition-from-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!