【问题标题】:How to populate a view models using a linq query ASP.NET MVC 5 Entity Framework如何使用 linq 查询 ASP.NET MVC 5 Entity Framework 填充视图模型
【发布时间】:2023-04-08 16:46:01
【问题描述】:

好的,这是MVC 5 ASP.NET Entity Framework Collect Form Data through Range Input 的后续行动,我的数据库结构由具有许多类别的调查、具有许多问题的类别、具有许多 QuestionResults 的问题和最后具有许多 CategoryResults 的 QuestionResults 组成,在 HomeController I通过 ViewModel 绑定模型,但我现在需要通过 Linq 的上下文使用我的实体填充它,任何帮助将不胜感激。

我需要用我的实体填充这个 ViewModel,它是在一个非常有价值的堆栈溢出贡献者的帮助下创建的,所有代码如下:

主要问题:如何将我的实体引入我的 SurveyVM ViewModel 实例?

视图模型

namespace MyApp
{
    public class SurveyVM
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<CategoryVM> Categories { get; set; }
    }

    public class CategoryVM
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<QuestionVM> Questions { get; set; }
    }

    public class QuestionVM
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public int Score { get; set; }
    }

    public class QuestionResult
    {
        public int ID { get; set; }
        public int QuestionId { get; set; }
        public int QuestionScore { get; set; }
    }
}

链接到实体和后续数据库的模型

public class Question
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public virtual Category Category { get; set; }
        public int CategoryId { get; set; }
        public virtual ICollection<QuestionResult> QuestionResult { get; set; }
        public virtual ICollection<QuestionFeedback> QuestionFeedback { get; set; }
    }
public class QuestionResult
    {
        public int Id { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public int QuestionScore { get; set; }
        //navigation properties
        public virtual ApplicationUser User { get; set; }
        public ICollection<CategoryResult> CategoryResult { get; set; }
        public virtual Question Question { get; set; }
        public int QuestionId { get; set; }
    }
public class CategoryResult
    {
        public int Id { get; set; }
        public int CategoryScore {get;set;}
        //navigation properties
        public virtual QuestionResult QuestionResult { get; set; }
        public int QuestionResultId { get; set; }

    }
public class Category
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public virtual Survey Survey { get; set; }
        public int SurveyId { get; set; }
        public virtual ICollection<Question> Question { get; set; }
        public virtual ICollection<CategoryFeedback> CategoryFeedback { get; set; }
    }

HomeController

public ActionResult IndexSurveyViewModel()
        {
            SurveyVM model = new SurveyVM()
            {
                ID = 1,
                Name = "Survey 1",
                Categories = new List<CategoryVM>()
                {
                    new CategoryVM()
                    {
                        ID = 1, 
                        Name = "Category A", 
                        Questions = new List<QuestionVM>()
                        {
                            new QuestionVM()
                            {
                                ID = 1, Title = "Question 1A", Score = 2
                            }, 
                                new QuestionVM()
                            {
                                ID = 2, Title = "Question 2A", Score = 4
                            }
                        }
                    },
                    new CategoryVM()
                    {
                        ID = 1, 
                        Name = "Category B", 
                        Questions = new List<QuestionVM>()
                        {
                            new QuestionVM()
                            {
                                ID = 3, Title = "Question 1B", Score = 3
                            }, 
                                new QuestionVM()
                            {
                                ID = 4, Title = "Question 2B", Score = 5
                            }
                        }
                    },
                    new CategoryVM()
                    {
                        ID = 1, 
                        Name = "Category C", 
                        Questions = new List<QuestionVM>()
                        {
                            new QuestionVM()
                            {
                                ID = 5, Title = "Question 1C", Score = 1
                            }, 
                                new QuestionVM()
                            {
                                ID = 6, Title = "Question 2C", Score = 3
                            }
                        }
                    }   
                }
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult IndexSurveyViewModel(SurveyVM model)
        {
            List<QuestionResult> results = new List<QuestionResult>();
            foreach (CategoryVM category in model.Categories)
            {
                foreach (QuestionVM question in category.Questions)
                {
                    results.Add(new QuestionResult()
                    {
                        Id = question.ID,
                        QuestionScore = question.Score
                    });

                }
            }
            return View(model);
        }

查看

@model STRA.Models.SurveyVM
@{
    Layout = null;
}

<!DOCTYPE html>


<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My app</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <style>
        .category {
            display: none;
            margin-left: 20px;
            margin-top: 10px;
        }

            .category:first-of-type {
                display: block;
            }

                .category:first-of-type button:last-of-type {
                    display: none;
                }

            .category:last-of-type button:first-of-type {
                display: none;
            }

        .question {
            margin-left: 20px;
            margin-top: 10px;
        }

        .buttons {
            margin: 20px;
        }

        input[type="text"] {
            width: 20px;
        }

        .slider {
            display: inline-block;
            width: 200px;
            margin-left: 20px;
        }
    </style>
</head>


<body>
    @using (Html.BeginForm())
    {
        @Html.HiddenFor(m => m.ID)
        @Html.DisplayFor(m => m.Name)
        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>
        }
        <input type="submit" />
    }


    <!-- JS includes -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

    <script type="text/javascript">

            $('.slider').each(function() {
                var v = $(this).closest('.question').find('input[type="text"]').val();
                $(this).slider({
                    value: v,
                    min: 1,
                    max: 5,
                    change: function (event, ui) {
                        $(this).closest('.question').find('input[type="text"]').val(ui.value);
                    }
                });
            });
            $('.next').click(function() {
                $(this).closest('.category').hide().next('.category').show();
            });
            $('.previous').click(function() {
                $(this).closest('.category').hide().prev('.category').show();
            });
    </script>
</body>
</html>

到目前为止我的代码:

var survey = from s in db.Surveys
                         from c in db.Categories
                         from q in db.Questions
                         where s.Id == c.SurveyId
                         where c.Id == q.CategoryId
                         select new SurveyVM
                         {
                             ID = s.Id,
                             Name = s.Title,
                             Categories = new List<CategoryVM>()
                             {
                                 new CategoryVM()
                                 {
                                     ID = c.Id,
                                     Name = c.Title,
                                     Questions = new List<QuestionVM>()
                                     {
                                         new QuestionVM()
                                         {
                                             ID = q.Id,
                                             Title = q.Title
                                         }
                                     }
                                 }
                             }
                         };

如何将我的实体引入我的 SurveyVM ViewModel 实例?

【问题讨论】:

  • 说实话我不太清楚如何处理它
  • 您基本上要求我们编写您的代码。 具体问题是什么?将其缩小到您需要了解的内容,并仅发布特定于问题的代码。
  • 对不起,我想我会发布相关的类,我正在尝试将我的实体绑定到 linq 语句并通过视图模型将其传递到视图中,我将按上述方式发布我的 linq 语句跨度>
  • 好的,如何将我的实体引入我的 SurveyVM ViewModel 实例?
  • @GertArnold 没有提出具体问题并不意味着这是一个代码审查问题。从我所做的编辑和我上面的 OP 评论可以看出,这个问题不属于 CR。

标签: c# asp.net asp.net-mvc linq entity-framework


【解决方案1】:

这可能会为您指明正确的方向,它使用 lambda 表达式。

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();

这不是我的想法,因为我没有任何东西可以测试它。

另外,我会考虑在您的视图中使用 EditorTemplates/DisplayTemplates 而不是循环,因为它会使您的代码更易于阅读。

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

【讨论】:

    【解决方案2】:

    当你有域模型并且每个域模型都有很多视图模型时,那么是使用Automapper 的正确时机。您可以在此处找到所有文档:

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

    【讨论】:

      猜你喜欢
      • 2017-02-08
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多