MVC 4 Code First ForeignKeyAttribute on property ... on type ... is invalid

I keep getting this error and I don't know why.

The ForeignKeyAttribute attribute on the "Ward" property of 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 must be a comma-separated property name of the foreign key.

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 someone help me resolve this?

+4
source share
1 answer

[ForeignKey("WardId")] indicates that the property used as the foreign key for the Ward table should be the WardId property in the BioSheetModel class.

You get an error because you did not define the WardId property in the BioSheetModel class.

Add

 public int WardId {get; set;} 

for a relationship with a zero / mandatory relationship or

 public int? WardId {get; set;} 

for a relationship with null / optional.

+11
source

Source: https://habr.com/ru/post/1502932/


All Articles