asp.net mvc EntityTypeConfiguration

时间:2017-12-08 17:52:40

标签: asp.net-mvc asp.net-mvc-5 ef-fluent-api

请对此有所了解...... 我有一个Employee and Department实体模型,具有如下所示的1对多关系

namespace Entities
{
    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Department Department { get; set; }
    }
}

namespace Entities
{
    public class Department
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public  ICollection<Employee> Employees { get; set; }
    }
}

为了使我的实体类更干净,我使用了EntityConfiguration类来声明如下的注释..

namespace Entities.EntityConfiguration
{
  public  class EmployeeConfiguration : EntityTypeConfiguration<Employee>
    {
        public EmployeeConfiguration()
        {
            Property(e => e.FirstName).IsRequired().HasMaxLength(10);

            Property(e => e.LastName).IsRequired().HasMaxLength(10);

HasRequired(a=>a.Department).WithMany(a=> a.Employees).Map(x=> x.MapKey("DepartmentID"));
        }
    }
}

员工控制器中“创建”视图的一部分如下所示

<div class="form-group">
           @Html.LabelFor(model => model.Department, "Department", htmlAttributes: new { @class = "control-label col-md-2" })
           <div class="col-md-10">
               @Html.DropDownList("Department", @ViewBag.Department as SelectList,"--Please Select--", htmlAttributes: new { @class = "form-control" })
               @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
           </div>
       </div>

在“创建”后期方法中,我得到如下所示的员工价值 enter image description here

上面,“部门”显示为空。

但我想拥有这样的价值观 enter image description here

我的问题是:如果我想在这里拥有“DepartmentID”,那么我必须更改我的员工模型类,如下所示。

namespace Entities
{
    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public int DepartmentID { get; set; }
        [ForeignKey("DepartmentID")]
        public Department Department { get; set; }
    }
}

即我必须在员工模型类中输入数据注释, 然后在EntityConfiguration类中指定相同的用途是什么。 实际上我想在“创建”Post方法中使用“DepartmentID”,但我不想用数据注释来混淆我的员工类。

另外,如何在“创建”帖子方法中访问“部门”实体值?

请提出您的建议以及其他任何方法。

非常感谢。

1 个答案:

答案 0 :(得分:0)

如果您的实体模型公开了像这样的DepartmentId:

public class Employee
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DepartmentID { get; set; }
    public Department Department { get; set; }
}

然后在[HttpGet]中构建ViewBag:

ViewBag.Departments = _RepoDepartment.Select(x => new SelectListItem {
   Text = x.IDToString(), 
   Value = x.Name 
}).ToList();

现在在你看来:

@Html.DropDownListFor(model => model.DepartmentID, ViewBag.Departments as IEnumerable<SelectListItem>)

现在,当您选择一个部门时,它的DepartmentID将被回发。还有其他方法可以做到这一点。