【问题标题】:How do I query only a single item from a database using LINQ?如何使用 LINQ 从数据库中仅查询单个项目?
【发布时间】:2009-04-08 08:17:39
【问题描述】:

我想要一个 LINQ-to-SQL 查询,它只返回一个项目,而不是它们的集合?

例如,我有一个具有特定名称的产品列表。数据库中没有名称重复的产品,因此我希望能够仅查询并返回该产品的该实例。

Products product = from p in _productContext.Products 
                   where p.name.Equals("BrownShoes") 
                   select p;

我该怎么做这样的事情?

【问题讨论】:

    标签: linq


    【解决方案1】:

    使用Single:

    Product product = _productContext.Products
                                     .Single(p => p.Name == "BrownShoes");
    

    Product product = _productContext.Products
                                     .Where(p => p.Name == "BrownShoes")
                                     .Single();
    

    Single 没有查询表达式语法,因此您必须将其作为普通扩展方法调用。此时,您的查询更简单,完全用点表示法编写,因此是上面的形式。你可以写成:

    Product product = (from p in _productContext.Products 
                       where p => p.Name == "BrownShoes"
                       select p).Single();
    

    但这有更多的绒毛。如果结果中没有一个元素,则会抛出异常。

    【讨论】:

    • 我更喜欢SingleOrDefault(),因为这样测试不存在就像检查null 一样简单,而不是处理异常。
    【解决方案2】:

    我建议使用IQueryable.SingleOrDefault()IQueryable.SingleOrDefault()IQueryable.Single() 将在多于一条记录时抛出异常,但如果 少于 一条记录,IQueryable.Single() 也会抛出一个异常。这意味着,如果您正在搜索单个记录并且无论出于何种原因它不存在,您都必须处理异常。

    更好的是 IQueryable.SingleOrDefault(),因为您只需检查 null:

    var employee = (from e in context.Employees
                    where e.ID == employeeID
                    select e).SingleOrDefault();
    
    if (employee == null)
    {
        // Cope with employee not found
    }
    
    // Do stuff with employee
    

    【讨论】:

      【解决方案3】:

      您需要使用.Single().SingleOrDefault()

      Products product = (from p in _productContext.Products where p.name.Equals("BrownShoes") select p).Single();
      

      Single() 会在没有 1 个产品时抛出异常,SingleOrDefault() 会在不存在时返回 null,如果有多个则抛出异常。

      【讨论】:

        【解决方案4】:
        Products product = (from p in _productContext.Products 
                            where p.name.Equals("BrownShoes") 
                            select p).FirstOrDefault();
        

        【讨论】:

          【解决方案5】:

          如果您确定会找到产品。如果没有找到产品会抛出异常:

          Products product = _productContext.Products
                                 .Single(p => p.name.Equals("BrownShoes"));
          

          或者,如果没有找到产品,产品将为空:

          Products product = _productContext.Products
                                 .SingleOrDefault(p => p.name.Equals("BrownShoes"));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-04-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-01-16
            相关资源
            最近更新 更多