SQL到LINQ / Lambda的翻译

时间:2015-02-25 03:13:51

标签: c# linq linq-to-sql

var sql =   from s in context.Sessions
            from q in context.Questions
                  .Where(q => q.SessionId == s.SessionId)
            from a in context.Answers
                  .Where(a => a.QuestionId == q.QuestionId)
            select new { q.QuestionId, q.QuestionContent, a.AnswerContent };

//转换为SQL为:

SELECT 
    [Extent1].[SessionId] AS [SessionId], 
    [Extent1].[QuestionId] AS [QuestionId], 
    [Extent1].[QuestionContent] AS [QuestionContent], 
    [Extent2].[AnswerContent] AS [AnswerContent]
    FROM  [dbo].[Question] AS [Extent1]
    INNER JOIN [dbo].[Answer] AS [Extent2] ON [Extent1].[QuestionId] = [Extent2].[QuestionId]
    WHERE [Extent1].[SessionId] IS NOT NULL

问题是:如何使用lambda表达式/ LINQ连接3个与SQL相同的表:

SELECT q.QuestionContent, a.AnswerContent, a.QuestionId
from Question as q
inner join Session as s
    on q.SessionId = s.SessionId
inner JOIN Answer as a
    on a.QuestionId = q.QuestionId
where q.SessionId = 976
group by a.QuestionId

2 个答案:

答案 0 :(得分:1)

试试这个

var sql = (db.Sessions.
             Join(db.Questions, q => q.SessionId, s => s.SessionId,
             (q, s) => new { q, s }).
             Join(db.Answers, a => a.s.QuestionId, qu => qu.QuestionId, (a, qu) => new { a, qu })
             .Where(m => m.qu.QuestionId == 1).Select (m => new {m.qu.AnswerContent,m.a.s.QuestionId,m.a.s.QuestionContent}));

希望有所帮助。

答案 1 :(得分:0)

试试这个:

var sql =
    from s in context.Sessions
    join q in context.Questions on s.SessionId equals q.SessionId
    join a in context.Answers on q.QuestionId equals a.QuestionId
    where q.SessionId == 976
    select new { q.QuestionId, q.QuestionContent, a.AnswerContent };