【问题标题】:MVC C# Lambda Join one to many select oneMVC C# Lambda Join 一对多选择一个
【发布时间】:2021-07-16 09:04:13
【问题描述】:

我需要加入 2 个表来列出类 DisplayProductList

public class DisplayProductList
{
    public Product_Details Product_Details { get; set; }
    public string Image_Path { get; set; }

    public DisplayProductList()
    {
        Product_Details = new Product_Details();
        Image_Path = string.Empty;
    }
}

表格

  1. 产品详情
  2. 产品图片

1 Product_Details 有许多 Product_Images 但我需要选择 Product_Images 的第一条记录加入

List<DisplayProductList> displayProductLists = new List<DisplayProductList>();
displayProductLists = db.Product_Details
    .Join(db.Product_Images.OrderBy(o => o.Product_Image_Seq),
    pd => pd.Product_Id,
    pi => pi.Product_Id,
    (pd, pi) => new { pd, pi })
    .Select(s => new DisplayProductList()
        {
            Product_Details = s.pd,
            Image_Path = s.pi.Product_Image_Path
        }).ToList();

这是我的命令。怎么改?

【问题讨论】:

    标签: c# asp.net-mvc lambda


    【解决方案1】:

    有两种变体。

    FirstOrDefault在投影中

    var displayProductLists = db.Product_Details
        .Select(pd => new DisplayProductList()
        {
            Product_Details = pd,
            Image_Path = db.Product_Images
                .Where(pi => pi.Product_Id == pd.Product_Id)
                .OrderBy(pi => pi.Product_Image_Seq)
                .Select(pi => pi.Product_Image_Path)
                .FirstOrDefault()
        })
        .ToList();
    

    更接近 SQL:

    var query = 
        from pd in db.Product_Details
        from pi in db.Product_Images
            .Where(pi => pi.Product_Id == pd.Product_Id)
            .OrderBy(o => o.Product_Image_Seq)
            .Take(1)
            .DefaultIfEmpty()
        select new DisplayProductList
        {
            Product_Details = pd,
            Image_Path = pi.Product_Image_Path
        };
    
    var displayProductLists = query.ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 2013-01-25
      • 1970-01-01
      相关资源
      最近更新 更多