asp.net - 如何将这两个模型连接到 View 模型中

标签 asp.net asp.net-core asp.net-core-mvc

这是我的第一个 ASP 项目,我真的很困惑如何将多个表连接到一个 View 模型中。我有一个名为项目的模型,它将用于创建新项目并将它们插入数据库中。

using System;

namespace vasttPM1.Models
{
    public class Project
    {
        public int ID { get; set; }
        public string ProjectName { get; set; }
        public string CreatedBy { get; set; }
        public DateTime CreateDate { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime Enddate { get; set; }
        public string Installer { get; set; }
        public int ProjectNumber { get; set; }
        public string ProjectManager { get; set; }
        public string CustomerName { get; set; }
        public string CustomerPhone { get; set; }
        public string CustomerEmail { get; set; }
        public string ProjectType { get; set; }
        public string Building { get; set; }
        public string Rooms { get; set; }
        public string ProjectDescription { get; set; }
        public int Status { set; get; }
    }
}

我在数据库中有一个名为 ProjectStatus 的静态表,其中包含与每个项目关联的一些字段。主要是“状态”和“百分比”字段。

所以我想做的是获取上面模型中的信息,并从项目状态表中获取状态百分比,其中project.status = projectstatus.id

然后将结果组合到 View 模型中。

这听起来很容易,但我真的很努力地思考如何完成这项工作。

有什么建议吗?

最佳答案

根据我的理解,您想要将两个表放入一个 View 模型中。为此,您需要使用所需的属性创建一个新的 View 模型类。例如:

public class ProjectViewModel
{
    public string ProjectName { get; set; }
    public string Status { set; get; }
    public int Percent { set; get; }
}

然后,您可以使用 Linq 查询将两个表连接在一起,并将它们选择到新对象中,如下所示:

var results = (from p in db.Project
              join ps in db.ProjectStatus on p.Status equals ps.Id
              select new ProjectViewModel()
              {
                  ProjectName = p.ProjectName,
                  Status = ps.StatusName,
                  Percent = ps.PercentComplete
              }).ToList();

这应该为您创建一个 ProjectViewModel 列表,然后您可以在 View 中使用它。我可能有一些属性或列名称不正确。我必须猜测它们在您的 ProjectStatus 表中可能是什么。

关于asp.net - 如何将这两个模型连接到 View 模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010205/

相关文章:

asp.net - 在没有管理员帐户的情况下保护 ELMAH

c# - ASP.NET MVC4 显示所有注册用户名

c# - 混合 SPA 和 ASP.NET MVC 路由

c# - 模拟的 SignInManager 未按预期工作

c# - 我如何使用标签助手来获取任意元素上的模型属性名称?

ASP.NET 中具有回发功能的 jQuery 模式对话框

c# - 使用更新面板时,保存按钮不起作用

c# - 从 Web API 核心下载文件 - Angular 7

visual-studio - NuGet 包显示黄色感叹号

c# - MVC 6 中是否缺少 Controller 脚手架?