如何从多个表中选择数据?

时间:2012-11-17 06:08:08

标签: linq

在我的MVC项目中,我有一些这样的表:

  • 表格(FormID, SectionID
  • 部分(SectionID, SectionName
  • SectionQuestion(SectionID, QuestionID
  • 问题(QuestionID, Content

表单有多个部分,部分有一些问题。

我可以得到FormID的所有问题。但我想得到一个模型的部分列表(包含问题)。

这意味着在视图中我想做这样的事情:

@Model IEnumerable<MedialForm.Models.Sections>

foreach (var section in Model)
{
     //Show questions
}
你能帮助我吗? :)

1 个答案:

答案 0 :(得分:0)

您将不会看到表单的部分列表,因为表单只能包含1个部分。 (即SectionID是在Form中定义的,而不是在Section中定义的FormID)。但是,以下Linq查询将为指定的FormID返回此部分以及相关的问题:

void Main()
{
    var sections = 
        new [] 
        {
            new Section { SectionID = 1, SectionName = "SectionName1" },
            new Section { SectionID = 2, SectionName = "SectionName2" }
        };

    var forms = 
        new []
        {
            new Form { FormID = 1, SectionID = 1 },
            new Form { FormID = 2, SectionID = 1 },
            new Form { FormID = 3, SectionID = 2 },
            new Form { FormID = 4, SectionID = 2 }
        };

    var questions =
        new[]
        {
            new Question { QuestionID = 1, Content = "Question1" },
            new Question { QuestionID = 2, Content = "Question2" }
        };

    var sectionQuestions =
        new[]
        {
            new SectionQuestion { SectionID = 1, QuestionID = 1 },
            new SectionQuestion { SectionID = 2, QuestionID = 1 },
            new SectionQuestion { SectionID = 2, QuestionID = 2 }
        };

    var formId = 4;

    var result = forms
        .Join(
            sections, 
            f => f.SectionID, 
            s => s.SectionID, 
            (f, s) => new { Form = f, Section = s })
        .Join(
            sectionQuestions, 
            jfs => jfs.Section.SectionID, 
            sq => sq.SectionID, 
            (jfs, sq) => new { Form = jfs.Form, Section = jfs.Section, sq.QuestionID })
        .Join(
            questions, 
            jfsq => jfsq.QuestionID, 
            q => q.QuestionID, 
            (jfsq, q) => new { Form = jfsq.Form, Section = jfsq.Section, Question = q })
        .Where(f => f.Form.FormID == formId)
        .GroupBy(f => f.Section.SectionID)
        .Select(grp => new { SectionID = grp.Key, Questions = grp.Select(g => g.Question)});

    Console.WriteLine($"For Form: {formId} the following sections with their questions were found: {String.Join(", ", result.Select(r => $"SectionID: {r.SectionID}, QuestionIDs: [{String.Join(", ", r.Questions.Select(q => q.QuestionID))}]"))}");
}

public class Form
{
    public Int32 FormID { get; set; }
    public Int32 SectionID { get; set; }
}

public class Section
{
    public Int32 SectionID { get; set; }
    public String SectionName { get; set; }
}

public class SectionQuestion
{
    public Int32 SectionID { get; set; }
    public Int32 QuestionID { get; set; }
}

public class Question
{
    public Int32 QuestionID { get; set; }
    public String Content { get; set; }
}

这将返回以下结果:

  

对于表格:4,发现以下带有问题的部分:SectionID:2,QuestionID:[1、2]