小编use*_*255的帖子

实体框架中的任何V计数

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
}
Run Code Online (Sandbox Code Playgroud)

我的要求是只检查给定的员工ID; 存在于表中或不存在.我不希望表中的行只是一个真或假.我正在使用Entity Framework而不是LINQ to Objects.

我一直在读关于任何和伯爵的事情,有点无法决定; 我应该使用哪一个?如上所示我的代码应该使用第一个还是第二个语句?

我读到使用Any(它转换为SQL中的Exists)更快,因为一旦它满足条件它停止迭代并返回结果而Count()(它转换为选择SQL中的Count(*))迭代所有然后返回结果.但是这个帖子哪个方法表现得更好:.Any()vs .Count()> 0? 说Count()针对Linq对象进行了优化,它的性能优于Any.

我确实探索了一些,并尝试使用下面的代码片段来获取时间

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 => …
Run Code Online (Sandbox Code Playgroud)

c# linq performance entity-framework

7
推荐指数
1
解决办法
5907
查看次数

标签 统计

c# ×1

entity-framework ×1

linq ×1

performance ×1