在C#中使用Join和Pivot在实体框架中或编写存储过程

时间:2018-09-12 07:13:58

标签: c# sql entity-framework linq lambda

我想创建一个自定义的联接表,并希望向列显示行。 我想获取邀请信息,这些信息是默认信息,但与人们对任何邀请给出的问题答案结合在一起。

我需要对列进行问答行。 (我认为我们应该使用数据透视,但我不确定。)

我无法找到使用lambda或linq在ef c#中执行此操作的方法。或者我正在使用sql server 2012,所以如果您为此目的给我sql语句,我将不胜感激。

这是我的桌子。

id | name       | surname  
---+------------+------------
 1 |    carl    | sagan  
 2 |    john    | wick   
 3 |    alex    | rony   
 4 |    mary    | olsen   

邀请

 id | name       | peopleid  | hasquestion | isdefault  
---+-------------+-----------+-------------+-----------
 1 |    inv1     | 1         |    0        |    1
 2 |    inv2     | 1         |    1        |    0
 3 |    inv3     | 2         |    0        |    0
 4 |    inv4     | 2         |    1        |    1
 5 |    inv5     | 2         |    1        |    0
 6 |    inv6     | 3         |    1        |    1
 7 |    inv7     | 4         |    0        |    1

问题

 id | text         
---+------------
 1 |    question 1    
 2 |    question 2       
 3 |    question 3        
 4 |    question 4
 5 |    question 5  

问题答案

id | invitationid | questionid  | answer
---+--------------+-------------+--------
 1 |    2         | 1           |    abc
 2 |    2         | 2           |    def
 3 |    2         | 3           |    ghi
 4 |    4         | 3           |    jkl
 5 |    4         | 4           |    mno
 6 |    5         | 1           |    prs    
 7 |    6         | 5           |    tuy    

我的结果表应该是:

id |  peoplename     | default   | question 1  | question 2 | question 3 | question 4 | question 5  
---+-----------------+-----------+-------------+------------+------------+------------+-----------
 1 |    carl sagan   | inv1      |    abc      |    def     |   ghi      |            |   
 2 |    john wick    | inv4      |    prs      |            |   jkl      |    mno     |   
 3 |    alex rony    | inv6      |             |            |            |            |    tuy
 3 |    mary olsen   | inv7      |             |            |            |            |    

1 个答案:

答案 0 :(得分:0)

您可以先运行此脚本来创建SQL过程。

CREATE PROCEDURE sp_get_question_answers
AS
SELECT 
[peoplename],
[invitation],
[question 1],
[question 2],
[question 3],
[question 4],
[question 5]
FROM 
(SELECT 
p.[name] + ' ' + p.surname AS [peoplename],
i.[name] AS invitation,
q.[text] question,
qa.answer
 FROM dbo.people p  
 INNER JOIN dbo.invitations i ON p.id = i.people_id
 INNER JOIN dbo.question_answers qa ON i.id = qa.invitation_id
 LEFT JOIN dbo.questions q ON qa.question_id = q.id)
 AS SourceTable
 PIVOT 
 (
 MAX(answer)
 FOR question  IN 
([question 1],
[question 2],
[question 3],
[question 4],
[question 5]) 
)AS PivotTable;
GO

然后,您可以通过实体框架执行过程。 IEnumerable<QuestionAnswer> answers = dbContext.FromSql<QuestionAnswer>("Exec sp_get_question_answers");

假设QuestionAnswer是一个具有与过程返回的属性匹配的属性的类。