3

我试图从 2 个表中在 Linq 中进行自然左连接

2张桌子

| questions |
+-----------+
| id        |
| question  |
+-----------+


|  answers  |
+-----------+
|  id       |
|  q_id (fk)|
|  answer   |
+-----------+

我试图为每个问题检索一行,但可以根据需要使用其他列

我不确定这是否可能

                      ID   | Question   | Answer 1 | Answer 2 | An....
| view      |       |-----------------------------------------------+
+-----------+       |  1   |   question | answer1  | answer2  | ... |
| id        |       |  2   |   question | answer1  | answer2  | ... |
| question  |       |  3   |   question | answer1  | answer2  | ... |
| answer1   |  or   |  4   |   question | answer1  | answer2  | ... |
| answer2   |       |  5   |   question | answer1  | answer2  | ... |
| answer3   |       |  6   |   question | answer1  | answer2  | ... |
| answer... |       |  7   |   question | answer1  | answer2  | ... |
+-----------+       |-----------------------------------------------+

我的 C# Linq

        var joinedTable =
        from questions in db.Results
        join answers in db.Answers on questions.id equals answers.result_id
            into answers
        select new 
        { 
           questions.id, 
           TOTAL_ANSWERS = answers.Count(), 
           questions.SurveyDateCreated, 
           (answers.ForEach(a=> a.answer) as "Answer" + i++)
        };
4

1 回答 1

0

您正在寻找的内容称为 PIVOT。最好的方法是在 SQL 中创建一个存储过程并在 SQL 中执行 PIVOT。使用 LINQ 是可能的,但很复杂。

使用 LINQ 进行数据透视:http: //madhukap.blogspot.com/2011/05/pivot-with-linq.html http://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using -linq

于 2012-11-15T19:07:01.897 回答