Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...