如何将具有多个连接的Linq表达式转换为方法语法或检索选择索引?

时间:2013-09-30 15:16:56

标签: c# linq lambda

我有一个(工作!)linq表达式:

from ca in db.CustomAnswer
join ss in db.SurveySubmission on ca.SubmissionId equals ss.Id
join cq in db.CustomQuestion on ca.QuestionId equals cq.Id
where (ss.SurveyId == request.SurveyId)
orderby ss.Submitted, cq.SortOrder
select new
{
    SubmissionId = ss.Id,
    Answer = ca.Answer
}

我想将select的索引添加到新对象中,例如

from ca in db.CustomAnswer
join ss in db.SurveySubmission on ca.SubmissionId equals ss.Id
join cq in db.CustomQuestion on ca.QuestionId equals cq.Id
where (ss.SurveyId == request.SurveyId)
orderby ss.Submitted, cq.SortOrder
select new
{
    SubmissionId = ss.Id,
    **Code = selectIndex,**
    Answer = ca.Answer
}

为此,我相信我需要先将查询转换为方法语法,以便我可以使用Select((q, index) => ...)表单。简单来说,我认为它应该是:

  db.SurveySubmission
    .Where(ss => ss.SurveyId == request.SurveyId)
    .OrderBy(ss => ss.Submitted)
    .Join(db.CustomAnswer, ss => ss.Id, ca => ca.SubmissionId, (ss, ca) => new { ss, ca })
    .Join(db.CustomQuestion, o => o.ca.QuestionId, cq => cq.Id, (o, cq) => new { o.ss, o.ca, cq })
    .OrderBy(q => q.cq.SortOrder)
    .Select((q, idx) => new {
                                SubmissionId = q.ss.Id,
                                Answer = q.ca.Answer,
                                Code = idx
                            });

然而,当评估表达式时,我得到一个错误:

  

LINQ to Entities无法识别该方法   “System.Linq.IQueryable 1[<>f__AnonymousTypef 3的System.Guid,System.String,System.Int32]]    选择并[d&GT; F_ AnonymousTypee 3,<>f__AnonymousTypef 3]   (System.Linq.IQueryable 1[<>f__AnonymousTypee 3 [My.Data.Namespace.SurveySubmission,   My.Data.Namespace.CustomAnswer,My.Data.Namespace.CustomQuestion],   System.Linq.Expressions.Expression 1[System.Func 3 [&LT;&GT;˚F _AnonymousTypee 3[My.Data.Namespace.SurveySubmission, My.Data.Namespace.CustomAnswer,My.Data.Namespace.CustomQuestion],System.Int32,<>f__AnonymousTypef 3的System.Guid,   System.String,System.Int32]]])”   方法,并且此方法无法转换为商店表达式。

我希望这对某人来说显而易见?我已经盯着它看了好几个小时,我能做出的唯一结论就是我不够聪明......任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

EF无法将其转换为SQL,因为SQL集是无序的;索引的想法对它没有任何意义。

而是使用EF查询完成所有获取索引,然后使用linq to objects查询中的索引:

var query = //your original query goes here

var finalQuery = query.AsEnumerable()
    .Select((answer, index) => new
        {
            answer.SubmissionId,
            answer.Answer,
            Code = index,
        });