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

3

我该如何解决这个问题?

'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个回答

2

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

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

考虑到您正在尝试使用从查询中检索到的值调用此函数,您很可能需要:

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

谢谢。之后我遇到了另一个问题。我已经在这个链接中解释了它。请访问它。 http://stackoverflow.com/questions/25833503/data-not-showing-in-kendo-mvc-grid - x19

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接