我的查询在.Net 3.5 SP1 中工作,直到我添加了一个连接。即使没有关联的用户实体,连接也允许从评论实体中进行选择。我收到以下错误:
LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable`1[XXX.YYY.BusinessLayer.User] DefaultIfEmpty[User](System.Collections.Generic.IEnumerable`1[XXX.YYY.BusinessLayer.User])' method, and this method cannot be translated into a store expression.
我使用 LinqPad 验证了查询在 .Net 4+(我认为!)中有效。
我在解决方案中的查询如下:
var comments = (from dic in _context.Comments
join u in _context.Users on dic.CommentUserId equals u.UserId into j1
from j2 in j1.DefaultIfEmpty()
where dic.Parent.Id == 406
select new { dic.CommentId, dic.CommentDate, dic.CommentText, j2.AccountName }).AsEnumerable()
.Select(x => new CommentInfo
{
CommentId = x.CommentId,
CommentDate = x.CommentDate,
CommentText = x.CommentText,
UserName = ActiveDirectoryUtil.GetUserDisplayName(x.AccountName)
});
我对 Linq 和 Lambda 还是陌生的,所以仍然在寻找解决方法。ActiveDirectoryUtil.GetUserDisplayName 是一个静态方法调用,用于进行查找以获取用户的显示名称。
添加以下行后问题出现了:
... into j1
from j2 in j1.DefaultIfEmpty()