繁体   English   中英

从数据库中删除满足条件的实体的最有效方法是什么?

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

AFAIK,没有使用谓词删除实体的直接方法,例如

DbSet.RemoveWhere(() => {})

我尝试了几种删除方法,但不知道哪种方法最有效。 你能指出我正确的方向吗?

我尝试的第一件事也是最基本的事情是:

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

在删除之前将用户加载到 memory。 我不喜欢这种方法。 我尝试的第二种方法是使用Z.EntityFramework.Plus package:

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

它声称删除对象而不加载它们,但我不知道这是否比第一种方法更好。 这也让人感觉不对,因为 efcore 应该有正确的方法来做到这一点。 我做的第三次尝试是这样的:

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

我不知道这是否会将用户加载到 memory 中,并且其中有一个讨厌的异步。 它还给出了以下例外:

"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");

通常RemoveRemoveRange适用于您已经拥有对象的Primary Key (通常是Id )的情况,在这些情况下,您可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM