返回实体和子集合的查询..子集合排序?

时间:2009-08-21 14:54:37

标签: c# linq-to-entities

如何创建一个将一个实体与一个集合一起返回的查询,并将该集合排序?我不在乎它是否是对DB的两次调用..我只需要最终结果是实体类型而不是匿名类型:

VAR

category = context.Categories.Where(c => c.categoryID == categoryID).Select(c => new {c,products = c.Products.OrderByDescending(p => p.priceDate)} )。首先();

但我想让上面的内容返回或转换为带有Products集合的类别..与匿名类型相关联。谢谢!

2 个答案:

答案 0 :(得分:0)

如果您的数据库中有正确的外键关系,那么对您的类别进行简单选择就足够了,然后您可以订购产品

Category category = context.Categories.Where(c => c.categoryID == categoryID).First();

List<Product> sortedProducts= context.Categories.products.OrderBy(...).ToList()

当你获得顶级对象时你的FK关系设置它也应该检索它的孩子(我没有使用linq-to-entities但是使用linq-to-sql我不能想象它在这方面不同) 我认为以上应该有效......

答案 1 :(得分:0)

你能把它放到类别课程中吗?像这样:

public parital class Category 
{
        public Ilist<Product> ProductsByPriceDate
        {
          get
          {
              return this.Products.OrderbyDescending(p= > p.priceDate).ToList();
          }
        }
    }
相关问题