1

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

  • 表格 ( FormID, SectionID)
  • 第 ( SectionID, SectionName)节
  • 部分问题 ( SectionID, QuestionID)
  • 问题(QuestionID, Content

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

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

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

@Model IEnumerable<MedialForm.Models.Sections>

foreach (var section in Model)
{
     //Show questions
}

你们能帮帮我吗?:)

4

1 回答 1

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

这将返回以下结果:

对于 Form: 4 找到以下部分及其问题:SectionID: 2, QuestionIDs: [1, 2]

于 2019-06-28T22:44:19.700 回答