【发布时间】:2010-11-01 23:54:21
【问题描述】:
我有一个严重嵌套的视图模型。我需要从 Entity Framework 4 填充它。我尝试创建一个大的 linq 语句来填充它,但它说它不识别 .ToList() 方法。它编译得很好。运行时错误是
LINQ to Entities does not recognize the method
'System.Collections.Generic.List`1[ProductDepartment] ToList[ProductDepartment]
(System.Collections.Generic.IEnumerable`1[ProductDepartment])' method,
and this method cannot be translated into a store expression.
在不进行数千次数据库调用的情况下填充此类内容的更有效方法是什么?
List<Product> Products {
int ID
string Name
...
List<Department> Departments {
int ID
string Name
}
List<Image> Images {
int ID
string Name
}
List<Price> Prices {
int ID
string Name
List<Version> Versions {
int ID
string Name
List<Pages> Pages {
int ID
string Name
} } } }
可怕的 Linq 代码看起来像这样
var myProducts = (from myProduct in DC.MyProducts
where p => p.productGroup == 1
select new Product {
ID = myProduct.ID,
Name = myProduct.Name,
Departments = (from myDept in DC.MyDepartments
where q => q.fkey = myProduct.pkey
select new Department {
ID = myDept.ID,
Name = myDept.Name
}).ToList(),
...
//Same field assignment with each nesting
}).ToList();
更新:
解决方法是删除所有 .ToLists(),反正效果更好。
现在我必须对最终产品进行过滤和排序。
【问题讨论】:
-
启用预加载,使用 .include();参考:blogs.msdn.com/b/adonet/archive/2008/10/07/…
-
这是一个非常好的主意,但它正在加载嵌套。我检查并删除了所有 .ToLists(),将返回类型更改为 IEnumerable,然后在对象上执行了 .ToList()。然后一切都开始流动。仍在寻找最好的方法来做到这一点。 :)
标签: c# entity-framework-4