这两个 EF 核心查询有什么区别?一个比另一个更好还是更快?

问题描述 投票:0回答:3

哪个更好、更快或更有效率?或者在这种情况下无关紧要?

account = await _dbContext.Accounts
     .FirstOrDefaultAsync(p => p.AccountId == account.AccountId);

account = await _dbContext.Accounts
    .Where(p => p.AccountId == account.AccountId)
    .FirstOrDefaultAsync();
c# performance entity-framework entity-framework-core linq-to-entities
3个回答
1
投票

或者在这种情况下无关紧要?

没关系。与网络调用相比,性能差异(如果有的话)可以忽略不计。并且这两个查询将被翻译成完全相同的 SQL,如下所示:

SELECT a."AccountId", a. ....
FROM "Accounts" AS a
WHERE a."AccountId" ==  @_some_var_name_0
LIMIT 1

有些 IDE(Resahrper/Rider)实际上会建议将第二个重构为第一个。


0
投票

这两种方法之间的性能差异可能很小,并且在大多数情况下可能并不重要。因此,它们之间的选择可以基于可读性、编码风格或个人喜好。


0
投票

在这种情况下,正如@Guru Stron 所说的那样并不重要。您可以使用此 tool 来帮助您可视化将由 LINQ 查询产生的 SQL 查询。

但是我更喜欢第一个选项,因为当你有多个条件时它更容易阅读:

account = await _dbContext.Accounts
    .Where(p => p.AccountId == account.AccountId)
    .Where(p => p.AccountName == account.AccountName)
    .Where(p => p.AccountNumber == account.AccountNumber)
    .Where(p => p.AccountValue == account.AccountValue)
    .FirstOrDefaultAsync();
© www.soinside.com 2019 - 2024. All rights reserved.