添加关系和导航属性

时间:2015-07-13 22:54:29

标签: asp.net-mvc entity-framework asp.net-mvc-4

如何配置或映射导航属性?

我有员工表,目前它确实正确显示EmployeeStatusId但是我想要EmployeeStatus Text以及EmployeeStatusId我将如何处理?

我有以下型号:

Employee.cs

 public class Employee
 {
        [Key]
        public int? RecordId { get; set; }
        public string company{ get; set; }
        public string Name{ get; set; }
        public int? EmployeeStatusId { get; set; }
 }

的employeeStatus:

public class EmployeeStatus
{
    public int Id{ get; set; }
    public string Name { get; set; }
}

的DbContext:

public class DataCenterDB : DbContext
{       
    public DbSet<Employee> Employees { get; set; }
    public DbSet<EmployeeStatus> EmployeeStatus { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().ToTable("Employee");
        modelBuilder.Entity<EmployeeStatus>().ToTable("EmployeeStatus");
        base.OnModelCreating(modelBuilder);
    }
}

2 个答案:

答案 0 :(得分:1)

首先,您应该以这种方式定义EmployeeStatus属性:

public class Employee
{
    // other properties

    [ForeignKey("EmployeeStatusId")]
    public virtual EmployeeStatus EmployeeStatus { get; set; }
    public int? EmployeeStatusId { get; set; }
}
public class EmployeeStatus
{
    public int Id{ get; set; }
    public string Name { get; set; }
}

然后在控制器操作方法中,您应该填充EmployeeStatus

的列表
ViewBag.StatusList = new SelectList(_statusService.GetAllStatus(), "Id", "Name");

最后在您的视图中,您可以使用此代码在下拉列表中显示数据:

<div class="form-group">
    @Html.LabelFor(model => model.EmployeeStatusId, new { htmlAttributes = new { @class = "form-control" } })
    <div>
        @Html.DropDownList("EmployeeStatusId", (SelectList)ViewBag.StatusList, "-- Select ---", new { @class = "form-control"})
        @Html.ValidationMessageFor(model => model.EmployeeStatusId, "", new { @class = "text-danger" })
    </div>
</div>

答案 1 :(得分:0)

在您的视图中使用:

@Html.DisplayFor(x => x.EmployeeStatus.Name)

这将获得模型的EmployeeStatus Name值。只要您的关系正确,实体框架就会自动链接它们。

在你的模特中

public class Employee
 {
    [Key]
    public int RecordId { get; set; }
    public string company{ get; set; }
    public string Name{ get; set; }
    public int EmployeeStatusId { get; set; }
    public virtual EmployeeStatus EmployeeStatus {get;set;}
 }

public class EmployeeStatus
{
    public int Id{ get; set; }
    public string Name { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
}

我在类中使用了关键字virtual,因此它知道将Employee实体链接到EmployeeStatus实体。 此外,如果它是外键关系,则EmployeeStatus ID不应该是可空的