Finding a recommendation for a 3-tier LINQ query in the Entity Framework

I currently have a LINQ query that correctly retrieves all the relevant survey questions and their associated answers. In this request, I use the .Include () method to get the answers. I like this approach because it makes the code in my view simple - basically I have @foreach for answers nested inside @foreach for questions.

Now I would like to add information specific to the response, such as # votes today, # votes this week and the total number of votes. Again, they will be retrieved and displayed for each answer of each question.

Is there an effective LINQ solution that would allow me to continue to use my .Include () method and my @foreach nested loops, or do I need to abandon the .Include () method and use joins to pull everything together?

If it matters for performance, it is written to .net MVC-3.

Thanks in advance for your opinions / suggestions.

+3
source share
1 answer

I like this approach because it makes the code in my view simple - basically I have @foreach for answers nested inside @foreach for questions.

. , Display Temapltes? # , , , , :

public class QuestionViewModel
{
    public int VotesToday { get; set; }
    public int VotesThisWeek { get; set; }
    public int TotalVotes { get; set; }
    public IEnumerable<ResponseViewModel> { get; set; }
}

IEnumerable<QuestionViewModel> , :

@model IEnumerable<AppName.Models.QuestionViewModel>
@Html.DisplayForModel()

~/Views/Shared/DisplayTemplates/QuestionViewModel.cshtml

@model AppName.Models.QuestionViewModel
<div>@Model.VotesToday</div>
<div>@Model.VotesThisWeek</div>
<div>@Model.TotalVotes</div>
@Html.DisplayFor(x => x.ResponseViewModel)

~/Views/Shared/DisplayTemplates/ResponseViewModel.cshtml:

@model AppName.Models.ResponseViewModel
<div>@Model.Body</div>

.

:

public class QuestionsController: Controller
{
    private readonly IQuestionsRepository _repository;
    public QuestionsController(IQuestionsRepository _repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        IEnumerable<Question> model = _repository.GetQuestions();
        IEnumerable<QuestionViewModel> viewModel = Mapper
            .Map<IEnumerable<Question>, IEnumerable<QuestionViewModel>>(model);
        return View(viewModel);
    }
}

, EF - , . , , ( ).

, AutoMapper ( Mapper.Map<TSource, TDest> ).

, : . , , , .

0

Source: https://habr.com/ru/post/1786769/


All Articles