LINQ to Entities无法识别方法'System.Threading.Tasks.Task`

时间:2014-09-14 00:39:19

标签: c# asp.net-mvc multithreading linq-to-entities asp.net-identity

我该如何解决这个问题?

  

发生了'System.NotSupportedException'类型的异常   EntityFramework.SqlServer.dll但未在用户代码中处理

     

其他信息:LINQ to Entities无法识别该方法   “System.Threading.Tasks.Task`1 [Jahan.Blog.Model.Identity.User]   FindByIdAsync(Int32)'方法,此方法无法翻译   进入商店表达。

 public virtual User User { get; set; }
 private IQueryable<ArticleGridViewModel> Query()
 {
    ArticleRepository repository = new ArticleRepository();
    IQueryable<ArticleGridViewModel> query = repository.FindAll().Select(article => new     ArticleGridViewModel
    {
       Tags = article.ArticleTags.Where(c => c.ArticleId == article.Id).Select(b => b.Tag).Distinct().ToList(),
       NumberOfComments = article.Comments.Count(c => c.ArticleId == article.Id),
       AttachmentFiles =article.AttachmentFiles.Where(a => a.ArticleId == article.Id).Distinct().ToList(),
       CreatedDate = article.CreatedDate,
       IsActive = article.IsActive,
       IsActiveNewComment = article.IsActiveNewComment,
       LikeCounter = article.LikeCounter,
       ModifiedDate = article.ModifiedDate,
       RateCounter = article.RateCounter,
       Title = article.Title,
       UserId = article.UserId,
       Comments = Comments.Where(c => c.ArticleId == article.Id).ToList(),



       User = AppUserStore.Instance.FindByIdAsync(article.Id).Result, // The error happened because of this line of code.

   });
   return query;
 }

 public virtual IQueryable<ArticleGridViewModel> QueryByCriteria(Expression<Func<ArticleGridViewModel, bool>> predicate = null, params Expression<Func<ArticleGridViewModel, object>>[] includeProperties)
    {
        IQueryable<ArticleGridViewModel> items = Query();
        if (includeProperties != null)
        {
            foreach (var includeProperty in includeProperties)
            {
                items = items.Include(includeProperty);
            }
        }
        if (predicate != null)
            return items.Where(predicate);
        return items;
    }
    public virtual IEnumerable<ArticleGridViewModel> FindAll(Expression<Func<ArticleGridViewModel, bool>> predicate = null, params Expression<Func<ArticleGridViewModel, object>>[] includeProperties)
    {
        List<ArticleGridViewModel> result = QueryByCriteria(predicate, includeProperties).ToList();
        return result;
    }

Picture of Error

1 个答案:

答案 0 :(得分:2)

.Select(x=>)语句内的所有内容都必须能够转换为SQL表达式。这就是为什么在某些情况下尝试使用.ToString()(示例)可能会失败并出现相同的错误。

基本上,EF不知道如何将System.Threading.Tasks.Task的对象转换为SQL语句。

鉴于您尝试使用从查询中检索到的值来调用它,您很可能需要

  1. 遍历.Select()方法的结果,并为每个结果运行此函数以设置User属性,或
  2. 自己在该行中实现逻辑而不是调用函数,就像在其他地方使用where子句一样。