c# - 使用 Entity Framework LINQ 有效检查数据库中是否存在记录

标签 c# entity-framework linq linq-to-sql

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

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

如果查询结果为空,则表示代码'xxx'的客户尚不存在。在 Entity Framework 中,有多种方法可以编写此内容,但我正在寻找 最接近上方的一个 . 注意:代码字段有唯一索引
  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();
  }

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

最佳答案

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

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

如果多个 ID 是有效结果,则无论 id 的类型如何,您的方法都应返回字符串/整数数组。是。您可以使用 .ToArray(); 返回一组 ID
 return context.Customers
               .Where(c => c.RecActive && c.Code == customerCode)
               .Select(c => c.id)
               .ToArray();

如果你不期望有多个 ID,你必须决定如果你得到多个结果怎么办:
  • FirstOrDefault()如果有多个结果,将返回第一个 ID 而不抛出。
  • SingleOrDefault()如果有多个结果阻止使用可能无效的 ID,则将抛出。

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

    关于c# - 使用 Entity Framework LINQ 有效检查数据库中是否存在记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48503979/

    相关文章:

    visual-studio-2010 - 更改 DataSet 中 NullValue 的默认行为

    c# - Visual Studio,调试多个线程之一

    C# System.Xml.Serialization - 仅使用 <a></a> 而从不使用 <a/>

    c# - 流利的 NHibernate : How do I map Many-to-Many Relationships with additional attributes on the relationship table?

    c# - 在大型项目中使用通用存储库/工作单元模式

    sql - 将抽象类和子类保存到数据库

    asp.net-mvc - 从命令运行查询是否违反了命令-查询分隔?

    c# - Azure 服务结构参与者依赖注入(inject)

    c# - 在 DataTable 中查找值的 Linq 方法

    c# - 如何将带有多个条件(带有 LIKE)的 SQL SELECT INNER JOIN 查询写入 LINQ to SQL