从数据库中删除满足条件的实体的最有效方法是什么? [英] What is the most effective way to delete entites that satisfy a condition from a database?
问题描述
AFAIK,没有直接的方法使用
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")));
在删除之前将用户加载到内存中.我不喜欢这种方法.我尝试的第二种方法是使用 Z.EntityFramework.Plus
包:
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()
声称删除对象而不加载它们,但是我不知道这是否比第一种方法更好.同样,这感觉不对,因为efcore应该具有适当的方法来执行此操作.我第三次尝试是这样的:
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));
我不知道这是否将用户加载到内存中,并且其中有一个讨厌的Async.它还给出了以下异常:
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."
推荐答案
我认为 ExecuteSqlRaw
更适合您:
_context.Database.ExecuteSqlRaw("DELETE FROM Users WHERE Name = @p0", "John");
通常 Remove
和 RemoveRange
适用于您已经具有 Primary Key
(通常是 Id
)的情况对象,在这种情况下,您可以执行以下操作:
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});
这篇关于从数据库中删除满足条件的实体的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!