Luis Valencia
Luis Valencia

Reputation: 33988

CodeFirst table is not being generated as I would expect

I have a class called Status, and I also have a class called ApplicantPositionHistory which has an OldStatus and a NewStatus.

However the table is being generated like this:

enter image description here

I would expect that the table has a newstatusid and oldstatusid, which should be foreign keys, but it generated those 2 columns duplicated.

 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; }

    }

Upvotes: 1

Views: 168

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

I think the problem is your non standard naming convention which results in problem when applying default mapping conventions so your FK columns are not paired with navigation properties and EF creates new ones.

Try this to manually pair navigation properties with your FK properties:

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

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

Upvotes: 1

Related Questions