Code First表没有像我期望的那样生成

时间:2011-10-19 12:02:38

标签: c# entity-framework entity-framework-4 entity-framework-4.1 ef-code-first

我有一个名为Status的类,我还有一个名为ApplicantPositionHistory的类,它有一个OldStatus和一个NewStatus。

然而,表格的生成如下:

enter image description here

我希望该表有一个newstatusid和oldstatusid,它应该是外键,但是它生成了那两个重复的列。

 public class ApplicationPositionHistory
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int ApplicationPositionHistoryID { get; set; }

        public ApplicantPosition applicantPosition { get; set; }

        [Column("oldStatusID")]
        public int oldStatusID { get; set; }

        [Column("newStatusID")]
        public int newStatusID { get; set; }

        public Status oldStatus { get; set; }

        public Status newStatus { get; set; }

        [StringLength(500, MinimumLength = 3, ErrorMessage = "Comments  should not be longer than 500 characters.")]
        [Display(Name = "Comments")]
        public string comments { get; set; }

        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date")]     
        public DateTime dateModified { get; set; }
    }

    public class Status
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int StatusID { get; set; }

        [StringLength(40, MinimumLength = 3, ErrorMessage = "Status  should not be longer than 20 characters.")]
        [Display(Name = "Status")]
        public string status { get; set; }

    }

1 个答案:

答案 0 :(得分:1)

我认为问题是您的非标准命名约定,这会导致应用默认映射约定时出现问题,因此您的FK列不会与导航属性配对,而EF会创建新的列。

尝试使用此手动将导航属性与FK属性配对:

[ForeignKey("oldStatusID")]
public Status oldStatus { get; set; }

[ForeignKey("newStatusID")]
public Status newStatus { get; set; }