Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Code First ForeignKeyAttribute on property ... on type ... is not valid

I keep getting this error and I do not know why.

The ForeignKeyAttribute on property 'Ward' on type 'BioSheet.Models.BioSheetModel' is not valid. The foreign key name 'WardId' was not found on the dependent type 'BioSheet.Models.BioSheetModel'. The Name value should be a comma separated list of foreign key property names.

public class Ward
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [ForeignKey("AddressId")]
    [Required]
    public virtual Address WardAddress { get; set; }

    [ForeignKey("BioSheetId")]
    public virtual List<BioSheetModel> BioSheets { get; set; }

    [Required]
    public String Code { get; set; }
}

public class BioSheetModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public String FirstName { get; set; }

    [Required]
    public String LastName { get; set; }
    public String Email { get; set; }

    [ForeignKey("WardId")]
    [Required]
    public Ward Ward { get; set; }

    public String CellPhoneNumber { get; set; }
    public String HouseNumber { get; set; }

    [Required]
    public String DoB { get; set; }

    [Required]
    public Address Address { get; set; }
    public String OtherInformation { get; set; }
    public String PreviousCallings { get; set; }

    [ForeignKey("TimePeriodId")]
    public virtual TimePeriod TimePeriods { get; set; }
    public String HomeWard { get; set; }
    public Boolean OkToText { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public DateTime TodaysDate { get; set; }

    [ForeignKey("EMPId")]
    public virtual EDUEMP EduEmp { get; set; }
    [ForeignKey("SingId")]
    public virtual Sing Singing { get; set; }

    [ForeignKey("MissionId")]
    public virtual Mission MissionIn { get; set; }
}

Can anyone help me resolve this?

like image 462
Travis Pettry Avatar asked Sep 19 '13 00:09

Travis Pettry


1 Answers

[ForeignKey("WardId")] indicates that the property to use as a foreign key to the Ward table should be the WardId property on the BioSheetModel class.

You're getting the error because you haven't defined a WardId property on the BioSheetModel class.

Add

public int WardId {get; set;}

for a non-nullable/required relationship, or

public int? WardId {get; set;}

for a nullable/optional relationship.

like image 153
ThinTim Avatar answered Oct 21 '22 11:10

ThinTim