关于在我的模型设计中使用“虚拟ICollection ......”?

时间:2013-12-16 20:11:20

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

我的asp.net mvc HR网络应用程序,在我的实体数据模型中,在一个页面剃刀视图中,我有多个数据模型加载和显示,例如,在The Employee razor视图中,我想要显示员工数据信息在顶部,但同样我也希望显示其他与该员工相关的数据,如Salary,Performance和Reveiw,所有这些相关数据都是分离的SQL表,这是不同的EF模型。

因此,为了简单起见,一个员工资料模型具有相关的薪资,绩效和评估模型(SQL表),因此我在员工资料模型中使用“虚拟ICollection”。

 In Employee Profile model: I have these codes:
 public class EmpProfile
 {
    public int ID { get; set; }
    [Display(Name = "Employee Name")]
    public string EmpName { get; set; }
    [Display(Name = "Employee Number")]
    public string EmpNum { get; set; }
    [Display(Name = "Employee Title")]
    public string EmpTitle { get; set; }
    [Display(Name = "Department")]


    public virtual ICollection<PerfPlan> PerfPlans { get; set; }
    public virtual ICollection<ProgReview> ProgReviews { get; set; }
    public virtual ICollection<ProgEvaluation> ProgEvaluations { get; set; }
    public virtual ICollection<DevelopPlan> DevelopPlans { get; set; }
}

在员工绩效模型中,我有这些代码(薪资和复习模型与此类似):

 public class Performance
 {
    public int ID { get; set; }
    public int EmpProfileID { get; set; }

    [Required(ErrorMessage = "{0} is required.")]
    [Display(Name = "Name*:")]
    public string EmpName { get; set; }
    [Required(ErrorMessage = "Please enter your Employee Number.")]
    [Display(Name = "Employee No.*:")]
    public string EmpNum { get; set; }
    ......
     public virtual EmpProfile EmpProfile { get; set; }
}

现在,在我构建它们之后,在我的性能控制器中,我在Create方法中找到了这个行代码:

ViewBag.EmpProfileID = new SelectList(db.EmpProfiles,“ID”,“EmpName”);

并在控制器生成的“创建”视图中,生成EmpProfileID下拉列表字段

@ Html.DropDownList(“EmpProfileID”,String.Empty)

任何人都可以告诉我为什么代码ViewBag.EmpProfileID = new SelectList(db.EmpProfiles,“ID”,“EmpName”);是否在Create methed中生成?

1 个答案:

答案 0 :(得分:0)

因为所有生成器都知道或关心的是EmpProfileID是一个不可为空的int,所以它会创建一个字段来编辑它。由于它是外键的id,因此它有助于为您提供EmpProfile ID的列表供您选择。如果您不希望此字段可直接编辑,则可以将其删除或将其更改为隐藏字段。您只需要记住,在检查ModelState.IsValid或验证失败之前,需要以某种方式设置它。

相关问题