【问题标题】:LINQ query is returning list when its not necessaryLINQ 查询在不需要时返回列表
【发布时间】:2023-02-09 20:03:28
【问题描述】:

所以我有一个显示我的产品列表的产品表。我在表中的每一行都有一个查看按钮,以便用户可以查看有关该特定产品的其他信息。为此,按钮会传递按下按钮的产品的 ID。这将允许我搜索我的数据库并找到显示此数据的记录。我知道每个产品都有一个唯一的 ID,所以我只需要返回一条记录。

我尝试使用:

  private void ViewProductDetails(int id)
    {
        product = productService.GetProductID(id);
      
        ViewProductPopup = true;
    }  



public Product GetProductByID(int id)
        {
            using (var context = _dbContextFactory.CreateDbContext())
            {
                return context.Products
                    .Where(x => x.ProductId == id);
            }
        }

但这不起作用,我收到“无法隐含地将类型 system.linq.iquertable<app.models.product> 转换为 app.models.product”的提示。存在显式转换(是否缺少转换?)'错误。所以我不得不使用一个 Product 类型的列表,当我只返回一个值时它没有意义:

  private void ViewProductDetails(int id)
    {
        productList = productService.GetProductID(id);
        selectedProduct = productList[0]; 
        ViewProductPopup = true;
    }  



public List<Product> GetProductByID(int id)
        {
            using (var context = _dbContextFactory.CreateDbContext())
            {
                return context.Products
                    .Where(x => x.ProductId == id)
                    .ToList();
            }
        }

在我的模型中,我有:

public partial class ProductFinderContext : DbContext
{
    public ProductFinderContext ()
    {
    }

    public ProductFinderContext (DbContextOptions<ProductFinderContext > options)
        : base(options)
    {
    }

   

    public virtual DbSet<Product> Products{ get; set; }

这是我的问题??

【问题讨论】:

    标签: c# linq return blazor-server-side


    【解决方案1】:

    令人震惊的是,LINQ 无法读懂您的想法并推断您希望它返回单个项目。

    IQueryable&lt;T&gt;.Where() 返回一个查询,该查询根据提供的表达式过滤其源。

    如果你知道它会产生一个元素,你需要调用一个合适的方法:Single()如果查询保证严格返回一个元素; SingleOrDefault() 如果结果可以是单个或空; First() 如果查询可能会产生多个结果,但您只需要一个; FirstOrDefault() 如果结果也可以为空。

    您可以在 Where() 之后链接这些方法,或者将表达式直接传递给它们:

    context.Products.Where(x => x.ProductId == id).Single()
    

    context.Products.Single(x => x.ProductId == id)
    

    应该产生相同的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2018-03-05
      • 2019-05-01
      • 2015-08-28
      • 1970-01-01
      相关资源
      最近更新 更多