简体   繁体   中英

SQL to LINQ/Lambda translation

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 };

//Translate to SQL as:

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

Question is:how to use lambda expression/LINQ to join 3 tables that do the same thing as SQL here:

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

Try this

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}));

Hope that help.

Try this:

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM