我试图让这个查询与EF一起工作,但它会引发异常:
var c = ac.Communities.OrderBy(o => o.Posts.Count())
.Skip(page*limit)
.Take(limit)
.Select(o => o.ToViewModel()).ToArray();
ToViewModel()
模型中的Community
方法如下所示:
public CommunityModel ToViewModel()
{
return new CommunityModel()
{
category = Category.Name,
created = CreationTime,
description = Description,
id = Id,
name = Name,
ownerId = Owner.Id,
postsCount = Posts.Count(),
score = Posts.Sum(o => o.Likes - o.Unlikes),
shortDescription = ShortDescription,
subscribersCount = Subscribers.Count(),
};
}
我做错了什么?
答案 0 :(得分:3)
实体框架无法翻译您在ToViewModel
内使用的方法。使用ToList()
急切加载结果,然后映射这些结果,避免EF尝试翻译SQL:
var c = ac.Communities.OrderBy(o => o.Posts.Count())
.Skip(page*limit)
.Take(limit)
.ToList()
.Select(o => o.ToViewModel()).ToArray();
答案 1 :(得分:1)
这是因为LINQ to Entities尝试将.ToViewModel
转换为SQL查询,而转换器无法识别该查询。
如果.Take
没有返回大量结果,那么您的最佳解决方案是将IQueryable
转换为List
,方法是将其更改为以下内容。
var c = ac.Communities.OrderBy(o => o.Posts.Count())
.Skip(page*limit)
.Take(limit)
.ToArray() // This will return a Community array
.Select(o => o.ToViewModel()) // This is a IEnumerable<CommunityModel>
.ToArray(); // This will cast // This is a cast for Community array