asp.net-mvc-3 – 实体框架,MVC 3,LINQ To Entities中的OrderBy

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 实体框架,MVC 3,LINQ To Entities中的OrderBy前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下查询
model.Page = db.Pages
    .Where(p => p.PageId == Id)
    .Include(p => p.Series
                   .Select(c => c.Comics
                                 .Select(col => col.Collection)))
    .SingleOrDefault();

虽然我现在需要通过名为“ReadingOrder”的属性来订购漫画,但这很有用.

我试过了:

model.Page = db.Pages
    .Where(p => p.PageId == Id)
    .Include(p => p.Series.Select(c => c.Comics.OrderBy(o => o.ReadingOrder)
                          .Select(col => col.Collection)))
    .SingleOrDefault();

但这会导致以下错误

@H_301_12@

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

任何想法这个错误意味着什么?

提前致谢

编辑:

我的模特:

public class Page
{
    public int PageId { get; set; }
    public string Title { get; set; }
    public ICollection<Series> Series { get; set; }
}

public class Series
{
    public int SeriesId { get; set; }
    public int PageId { get; set; }
    public string Title { get; set; }
    public Page Page { get; set; }
    public ICollection<Comic> Comics { get; set; }
}

public class Comic
{
    public int ComicId { get; set; }
    public string Title { get; set; }
    public int ReadingOrder { get; set; }
    public string Subtitle { get; set; }
    public int CollectionId { get; set; }
    public Collection Collection { get; set; }

}

public class Collection
{
    public int CollectionId { get; set; }
    public string Title { get; set; }
    public ICollection<Comic> Comics { get; set; }
}

解决方法

例外情况“…包含路径表达式必须引用导航属性…”基本上抱怨c.Comics.OrderBy不是导航属性. (我认为这是合法的投诉.)

实际上,EF不支持在预先加载语句(Include)中应用排序(以及过滤).

所以,你可以做什么?

选项1:

加载实体后在内存中排序:

model.Page = db.Pages
    .Where(p => p.PageId == Id)
    .Include(p => p.Series.Select(c => c.Comics
                          .Select(col => col.Collection)))
    .SingleOrDefault();

if (model.Page != null)
{
    foreach (var series in model.Page.Series)
        series.Comics = series.Comics.OrderBy(c => c.ReadingOrder).ToList();
}

很丑,但是因为你显然只是通过id加载一个Page对象,它可能比以下选项更快(LINQ to Objects in memory)(如果Series和Comics集合不是特别长).

选项2:

在混合了eager和explicite加载的部分中细分查询

model.Page = db.Pages
    .Where(p => p.PageId == Id)
    .Include(p => p.Series) // only Series collection is included
    .SingleOrDefault();

if (model.Page != null)
{
    foreach (var series in model.Page.Series)
        db.Entry(series).Collection(s => s.Comics).Query()
          .Include(c => c.Collection)
          .OrderBy(c => c.ReadingOrder)
          .Load(); // one new DB query for each series in loop
}

选项3:

投影?

Herehere顺便说一下复杂的危险包括多个导航属性链.它可以加载大量重复数据. Include确保您只有一次DB往返,但可能需要更多传输数据. Explicite加载有多个往返,但总共可能有更少的数据.

(我知道,我给了你这个包括……选择……选择……选择……链,但我怎么知道你会认真对待我:).那么,根据嵌套集合的大小,它仍然是最佳选择.)

原文链接:https://www.f2er.com/aspnet/249324.html

猜你在找的asp.Net相关文章