EF代码首先加载和OrderBy问题 [英] EF Code first Eager loading and OrderBy problem

查看:146
本文介绍了EF代码首先加载和OrderBy问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体叫做Category和Product,具有1:n关系。



我想要得到一个类别,其孩子是有序的。 >

这是我的linq:

  _db.Categories.Where(c => ; c.CategoryID == catID)
.Include(c => c.Products.OrderBy(p => p.ProductID))
.SingleOrDefault();

由于orderby,此查询执行以下异常。


包含路径表达式必须将
引用到
上定义的导航属性。使用虚线路径
参考导航属性和
选择运算符收集
导航属性。参数名称:
路径



解决方案

加载数据不能被排序或过滤。那就是linq-to-entities的限制,而在数据库中如何排序关系的唯一方法是使用投影:

  var data = _db.Polls 
.Where(c => c.CategoryID == pollID)
.Select(c => new
{
Pool = c,
产品= c.Products.OrderBy(p => p.ProductID)
})
.SingelOrDefault();

您可以投射到匿名或自定义类型,但无法投影到映射类型(例如投票)。



另一种方法是将其划分为两个查询并使用显式加载:

  var poll = _db.Polls.SingleOrDefault(c => c.CategoryID == pollID); 
_db.Entry(poll).Collection(c => c.Products)
.Query()
.OrderBy(p => .ProductID)
.Load );


I have two entities called Category and Product with 1:n relation.

I want to get a Category with its childs that childs be in order.

This is my linq:

 _db.Categories.Where(c => c.CategoryID == catID)
    .Include(c => c.Products.OrderBy(p => p.ProductID))
    .SingleOrDefault();

This query enforce with the below exception because of orderby.

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

解决方案

Eager loaded data cannot be ordered or filtered. That is linq-to-entities limitation and the only way how to order relations in the database is by using projection:

var data =  _db.Polls
               .Where(c => c.CategoryID == pollID)
               .Select(c => new 
                   {
                       Pool = c,
                       Products = c.Products.OrderBy(p => p.ProductID)
                   })
               .SingelOrDefault();

You can project to anonymous or custom type but you cannot project to mapped type (for example Poll).

Another way is dividing this to two queries and use explicit loading:

var poll = _db.Polls.SingleOrDefault(c => c.CategoryID == pollID);
_db.Entry(poll).Collection(c => c.Products)
               .Query()
               .OrderBy(p =>.ProductID)
               .Load();

这篇关于EF代码首先加载和OrderBy问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆