您需要使用视图模型。视图模型与 MV* 架构模式相关,用于将数据传递到视图或从视图传递数据。我将尝试用简单的术语来解释它。假设您有两个表:
员工
---------------------------------------
| Id | Name | Designation |
---------------------------------------
| 1 | John Doe | Software Engineer |
---------------------------------------
| 2 | John Smith | Test Engineer |
---------------------------------------
工资
----------------------------------------
| Id | EmployeeId | EmployeeSalary |
----------------------------------------
| 1 | 1 | $10,000 |
----------------------------------------
| 2 | 2 | $10,000 |
----------------------------------------
现在要在您的代码中访问这两个表,您已经使用 ORM 创建了数据实体,它将创建两个类:
Employee.cs
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
}
Salary.cs
public class Salary
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public long EmployeeSalary { get; set; }
}
现在要使用这两个模型在 UI 上表示有意义的数据,您可以创建一个包含所有必要数据实体的 ViewModel 并将其通过控制器传递给视图:
EmployeeViewModel.cs
public class EmployeeViewModel
{
public Employee EmployeeDetail { get; set; }
public Salary EmployeeSalaryDetail { get; set; }
}
员工控制器:
public class EmployeeController
{
public ActionResult Index()
{
var model = new EmployeeViewModel();
return View(model);
}
}
对于数据实体和视图模型之间的显着差异,请检查此; Is it possible to create view models by out of models created from database tables using entity framework DB first approach?