Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...