繁体   English   中英

使用实体框架 LINQ 有效检查数据库中是否存在记录

[英]Efficiently check if record exists in database using Entity framework LINQ

我需要使用实体框架检查客户的代码是否已经存在于数据库中。 理想情况下,我会像这样编写简单的 sql 查询:

select id from dbo.Customer where RecActive = 1 and Code = 'xxx';

如果查询结果为空,则表示代码'xxx'的客户尚不存在。 在实体框架中,有多种方法可以编写它,但我正在寻找最接近上面的一种 注意:代码字段上有唯一索引

  using (var context = new CustomerContext())
  {
    // not very efficient as it reads all columns
    return context.Customers.Where(c => c.RecActive && c.Code == customerCode).SingleOrDefault() != null ? true : false;

    return context.Customers.Where(c => c.RecActive && c.Code == customerCode).Count() > 0 ? true : false;

    // translates to this query:
    // exec sp_executesql N'SELECT [Limit1].[Id] AS [Id]
    // FROM ( SELECT TOP (2) 
    //        [Extent1].[Id] AS [Id]
    //        FROM [dbo].[Customer] AS [Extent1]
    //        WHERE ([Extent1].[RecActive] = 1) AND (([Extent1].[Code] = 
    //          @p__linq__0) OR (([Extent1].[Code] IS NULL) AND 
    //          (@p__linq__0 IS NULL)))
    //        )  AS [Limit1]',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'xxx'
    int a = context.Customers.Where(c => c.RecActive && c.Code == customerCode).Select(c => c.Id).SingleOrDefault();             
    return a > 0 ? true : false;

    return context.Customers.Where(c => c.RecActive && c.Code == customerCode).Any();
  }

也许还有其他好的(性能替代方案)? 注意:我必须使用实体框架 linq 而不是原始查询(我真的很喜欢),因为 linq 在整个项目中始终如一地使用。

如果您只想检查是否存在,请使用.Any() 如果要检索符合条件的 ID,请使用Select ,例如:

 context.Customers
        .Where(c => c.RecActive && c.Code == customerCode)
        .Select(c => c.id);

如果多个 ID 是有效结果,则无论id的类型是什么,您的方法都应返回一个字符串/整数数组。 您可以使用.ToArray();返回一个 ID 数组.ToArray();

 return context.Customers
               .Where(c => c.RecActive && c.Code == customerCode)
               .Select(c => c.id)
               .ToArray();

如果你期望有多个 ID,你必须决定如果你得到多个结果怎么办:

  • 如果有多个结果, FirstOrDefault()将返回第一个 ID 而不抛出。
  • 如果有多个结果阻止使用可能无效的 ID,则SingleOrDefault()将抛出。

例如:

return context.Customers.Where(c => c.RecActive && c.Code == customerCode)
               .Select(c => c.id)
               .SingleOrDefault();

由于您的代码会忽略实际 ID,并且仅返回其存在的true / false指示,因此您可以通过一次调用Any

return context.Customers.Any(c => c.RecActive && c.Code == customerCode);

暂无
暂无

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

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