在实体框架中任何Vs计数

本文关键字:Vs 计数 任何 实体 框架 | 更新日期: 2023-09-27 17:52:52

bool isEmployeeFound;
DbContext DatabaseContext = new DbContext(DatabaseConnectionString);
using (DatabaseContext )
{
    isEmployeeFound= DatabaseContext .Persons.Any(p => p.ExternalId == "123"); -- 1st statement
    isEmployeeFound= DatabaseContext .Persons.Count(p => p.ExternalId == "123") > 0; --2nd statement
}

我的要求是只检查如果给定的员工Id;是否存在于表中。我不希望从表的行只是一个真或假。我正在使用实体框架,而不是LINQ到对象。

我一直在看Any和Count,有点无法决定;我应该用哪一个?如上所示,我应该使用第一个还是第二个语句?

我读到使用Any(它转换为SQL中的存在)更快,因为一旦它满足条件,它就会停止迭代并返回结果,而Count()(它转换为SQL中的选择Count(*))迭代所有,然后返回结果。然而,这篇文章哪个方法性能更好:.Any() vs .Count()>0?表示Count()针对Linq对象进行了优化,其性能优于任何.

我做了更多的探索,并尝试使用下面的代码片段获取时间

using (var _dbContext = new DbContext())
{
    string caregiverId = "2301001";
    string clientPhoneNumber = "9795397674";
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    bool iscareGiverFoundWithAny = _dbContext.Persons.Any(p => p.ExternalId == caregiverId);
    bool isClientPhoneNumberFoundWithAny = _dbContext.PhoneNumbers.Any(ph => ph.Number == clientPhoneNumber);
    var testResult1 = stopwatch.Elapsed;
    stopwatch.Restart();
    bool iscareGiverFoundWithCountExt = _dbContext.Persons.Count(p => p.ExternalId == caregiverId) > 0;
    bool isClientPhoneNumberFoundWithCountExt = _dbContext.PhoneNumbers.Count(ph => ph.Number == clientPhoneNumber) > 0;
    var testResult2 = stopwatch.Elapsed;
    stopwatch.Stop();
    Console.WriteLine("Any " + testResult2.TotalSeconds); -- value for this line is coming as 0.0276239
    Console.WriteLine("Count Ext. " + testResult3.TotalSeconds); -- value for this line is coming as 0.0054292
    Console.ReadLine();
}

在运行上面的代码时,它显示Count更快。我很困惑。

的想法吗?

在实体框架中任何Vs计数

简短的回答是:坚持使用Any()。

你可以安全地忽略你引用的帖子,因为它不是特定于实体框架。当在简单集合之上使用LINQ时,是的,可能会有其他考虑。但是当使用LINQ查询数据库时,您需要避免不必要地遍历额外的数据库记录。

在本例中,您说Count()被证明比Any()快。但是,至少在数据库性能方面,您所经历的差异是如此之小,以至于您可以说在这种情况下获得了相同的性能。

实际上,如果您的表很小,或者您正在搜索的列被正确索引并且返回的记录很少,那么您可以期望Any()和Count()的性能相当相似。

但是假设您有一个大表,并且您的ExternalId列没有索引,那么您将不可避免地注意到Any()大大优于Count()。

要点:最佳情况场景(如果您的数据模型经过优化),两个选项的执行可能相似。在最坏的情况下,Any()绝对优于Count()。

除非EF引入了严重的SQL生成错误,否则永远不会有Count()大大优于Any()的情况。因此,为了安全起见,我建议您坚持使用Any().

在这种情况下

.Any(p => p.ExternalId == "123");
.Count(p => p.ExternalId == "123") > 0;

Any仍然表现更好。

我个人建议您尝试从hibernate中获取执行的sql和计时。