我正在尝试从 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++)
};
最佳答案
您正在寻找的是 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
关于c# - 自然加入.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13400652/