NotSupportedException:LINQ to Entities无法识别该方法

时间:2017-01-03 00:38:10

标签: c# .net entity-framework linq

我试图让这个查询与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(),
    };
}

我做错了什么?

2 个答案:

答案 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