MVC5 结合 db .Include 和 OrderBy

MVC5 combine db .Include with OrderBy

在我的控制器中,我像这样添加了 Balances 和 RZiS

Analysis1Full analysis1Full = db.Analysis1Full
                                .Include(u => u.Balance)
                                .Include(r => r.RZiS)
                                .SingleOrDefault(u => u.Analysis1FullId == id);
//enter code here

它给了我正确的对象。关键是我想按字符串字段(年)对余额进行排序。但它给了我一个错误:

Analysis1Full analysis1Full = db.Analysis1Full
                                .Include(u => u.Balance.OrderBy(y => y.Year))
                                .Include(r => r.RZiS)
                                .SingleOrDefault(i => i.Analysis1FullId == id);

错误:

An exception of type 'System.ArgumentException' occurred in EntityFramework.dll but was not handled in user code

Additional information: 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.

之所以会抛出异常,无非是因为它就是这么设计的。根据MSDNInclude()指定要包含在查询结果中的相关对象。

要让子项按顺序排列,您可以在访问它们时添加 OrderBy(),否则您需要在不同的查询中加载它们。

我是这样解决的...它正在工作

Analysis1Full analysis1Full = db.Analysis1Full.Find(id);

        analysis1Full.Balance = db.Balances.Where(t=>t.Analysis1FullId == analysis1Full.Analysis1FullId).OrderBy(y=>y.Year).ToList();
        analysis1Full.RZiS = db.RZiS.Where(t => t.Analysis1FullId == analysis1Full.Analysis1FullId).OrderBy(y => y.Year).ToList(); 

您认为这是个好方法吗?