如何在多表LINQ查询中添加OrderBy子句?

时间:2017-01-31 11:07:05

标签: c# linq

这是我的LINQ查询与lambda表达式工作正常:

var query = this.context.Blocks.Where(o => 
    o.IsActive && o.ProductSizes.Any(x => 
        x.SectionProductSizes.Any(y => 
            && y.SectionID == queryCriteria.SectionId y.Section.SizeTypeID == o.SizeTypeID
        )
    )
);

我们如何在SectionProductSizes表中的DisplayOrder列上添加排序?

添加用于此的模型类:

public partial class Blocks
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int SizeTypeID { get; set; }
    public int DisplayOrder { get; set; }
    public virtual ICollection<ProductSize> ProductSizes { get; set; }
}

public partial class ProductSize
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ProductID { get; set; }
    public int ProductSizeID { get; set; }
    public int DisplayOrder { get; set; }
    public virtual Product Product { get; set; }
    public virtual ICollection<SectionProductSize> SectionProductSizes { get; set; }
}

public partial class SectionProductSize
{
    public int SectionProductSizeID { get; set; }
    public int SectionID { get; set; }
    public int ProductSizeID { get; set; }
    public int DisplayOrder { get; set; }
    public virtual Section Section { get; set; }
}

public class Section
{
    public int ProductID { get; set; }
    public int SizeTypeID { get; set; }
    public int DisplayOrder { get; set; }
}

2 个答案:

答案 0 :(得分:0)

如果没有看到您的模型,很难回答这个问题,但是根据您所提供的内容,您希望能够正常工作。

var query = this.context.Blocks.Where(o =>
                        o.IsActive && o.ProductSizes.Any(x =>
                        x.SectionProductSizes.Any(y =>
                        && y.SectionID == queryCriteria.SectionId y.Section.SizeTypeID == o.SizeTypeID
                        )
                      )
                    ).OrderBy(x => x.SectionProductSizes.DisplayOrder); 

答案 1 :(得分:0)

我通过将lambda表达式查询转换为普通的LINQ查询解决了这个问题:

        var query = from bl in this.dbContext.Blocks
                    join ps in this.dbContext.ProductSizes on bl.Id equals ps.ModularContentBlockID
                    join sp in this.dbContext.SectionProductSizes on ps.Id equals sp.ProductSizeID
                    join se in this.dbContext.Sections on sp.SectionID equals se.Id
                    where bl.IsActive 
                        && se.SectionSizeTypeID == bl.SectionSizeTypeID
                        && sp.SectionID == queryCriteria.SectionId 
                    orderby sp.DisplayOrder
                    select bl;