我该如何解决这个问题?
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Threading.Tasks.Task`1[Jahan.Blog.Model.Identity.User] FindByIdAsync(Int32)' method, and this method cannot be translated into a store expression.
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;
}
最佳答案
.Select(x=>)
语句中的所有内容都必须能够转换为 SQL 表达式。这就是为什么尝试使用 .ToString()
(示例)在某些情况下可能会失败并出现相同的错误。
基本上,EF 不知道如何将 System.Threading.Tasks.Task 的对象转换为 SQL 语句。
鉴于您正在尝试使用从查询中检索到的值来调用它,您很可能需要要么
- 循环 .Select() 方法的结果并为每个结果运行此函数以设置用户属性,或者,
- 自己在该行中实现逻辑,而不是调用函数,就像您在其他地方使用 where 子句那样。
关于c# - LINQ to Entities 无法识别方法 'System.Threading.Tasks.Task`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829073/