How to populate a view models using a linq query ASP.NET MVC 5 Entity Framework

前端 未结 2 1605
终归单人心
终归单人心 2020-12-20 09:27

Ok so this is a follow-up from MVC 5 ASP.NET Entity Framework Collect Form Data through Range Input , My Database Structure Consists of a Survey Having Many Categories, A Ca

相关标签:
2条回答
  • 2020-12-20 09:43

    This might point you in the right direction, its using lambda expressions.

    List<SurveyVM> surveys = DbContext.Survey.Select(s=> new SurveyVM {
        ID = s.ID,
        Name = s.Name,
        Categories = s.Category.Select(c => new CategoryVM {
            ID = c.ID,
            Name = c.Name,
            Questions = c.Question.Select(q=> new QuestionVM {
                ID = q.ID,
                Title = q.Title,
                Score = q.Score
            }).ToList()
        }).ToList()
    }).SingleOrDefault();
    

    This is off the top of my head as I dont have anything to test it with.

    Also as a side note I would look at using EditorTemplates/DisplayTemplates instead of your loop in your view as it will make your code easier to read.

    for (int i = 0; i < Model.Categories.Count; i++)
        {
            <div class="category">
                @Html.HiddenFor(m => m.Categories[i].ID)
                @Html.DisplayFor(m => m.Categories[i].Name)
                @for (int j = 0; j < Model.Categories[i].Questions.Count; j++)
                {
                    <div class="question">
                        @Html.HiddenFor(m => m.Categories[i].Questions[j].ID)
                        @Html.DisplayFor(m => m.Categories[i].Questions[j].Title)
                        @Html.TextBoxFor(m => m.Categories[i].Questions[j].Score)
                        <div class="slider"></div>
                    </div>
                }
                <div class="buttons">
                    <button type="button" class="next">Next</button>
                    <button type="button" class="previous">Previous</button>
                </div>
            </div>
        }
    
    0 讨论(0)
  • 2020-12-20 10:04

    When you have Domain models and each of domain model have a lot of view models then it is the right time to use Automapper. All documentation you can find here:

    https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

    0 讨论(0)
提交回复
热议问题