我正在尝试使用Visual Studio 2017实体框架核心构建一个Web应用程序。我想将两个模型组合成一个视图。我有2个班 - 公司和我想要合并的员工。我希望员工信息与公司信息一起显示。什么是最优雅的方法?我很努力,因为这是我的第一个网络应用程序。
这是我的基本代码:
型号:
var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
app.use(serveStatic(path.join(__dirname, 'public')))
app.listen(3000)
这是我的控制者:
using System;
using System.Collections.Generic;
namespace Company.Model
{
public class Company
{
public int CompanyID { get; set; }
public string CompanyWebsite { get; set; }
public string CompanyPresident { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public string Email { get; set; }
}
}
答案 0 :(得分:1)
您应该创建一个包含所需属性的新模型。例如如下:
public class CompanyModel
{
public int CompanyID { get; set; }
public string CompanyWebsite { get; set; }
public string CompanyPresident { get; set; }
public Employee Employee { get; set; }
}
var company = await _context.Companies
.Include(s => s.CompanyEmployee)
.ThenInclude(e => e.Employee)
.AsNoTracking()
.SingleOrDefaultAsync(m => m.CompanyID == id);
//Bind data from company into CompanyModel
答案 1 :(得分:0)
可以找到这些事情的一个很好的例子here我建议在公司模型中添加
public Company(){ Employee = new HashSet<Employee>(); }
public virtual ICollection<Employee> Employee (get;set);
并添加到员工
[ForeignKey("Company")]
public int CompanyId{get;set;}
public virtual Company Company { get; set; }
除了必须在DBContext类中添加绑定而不是控制器
public class CompanyContext : DbContext {
public DbSet<Company> Companies { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>(entity =>
{entity.HasOne(d => d.Company)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.CompanyId);
});
}
}
modelBuilder的代码可能需要进行一些更改,以满足您的需求和模型