Chris Halcrow
Chris Halcrow

Reputation: 31960

Entity Framework - The foreign key component ... is not a declared property on type

I get this error:

The foreign key component 'SubdivisionHOAId' is not a declared property on type 'SubdivisionHOA'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

Here is my model. I don't understand what I need to do, as my understanding is that if I've specified [ForeignKey("SubdivisionsHOA")], it refers to my navigation property in the same class, so shouldn't it try to link on the 'Id' of SubdivisionHOA? I've been grappling with this for hours:

public partial class ContentArticleHOAsubdivision
{
    public int Id { get; set; }
    [ForeignKey("ContentArticleHOA")]
    public long ContentArticleId { get; set; }
    [ForeignKey("SubdivisionsHOA")]
    public short SubdivisionHOAId { get; set; }

    public virtual ContentArticleHOA ContentArticleHOA { get; set; }
    public virtual ICollection<SubdivisionHOA> SubdivisionsHOA { get; set; }
}

public partial class SubdivisionHOA
{
    [Key, ForeignKey("TopTierDivisionHOA")]
    public short Id { get; set; }
    public string Name { get; set; }

    public virtual TopTierDivisionHOA TopTierDivisionHOA { get; set; }
}

Upvotes: 1

Views: 3844

Answers (2)

Dev
Dev

Reputation: 1156

By now you have solved this but for anyone with the same problem here is the solution.

The ForeignKey attribute attribute should be on your other class SubdivisionHOA

Your ContentArticleHOAsubdivision class has a list of SubdivisionHOA and you don't need to add a Foreign Key to the List of values. You add the ForeignKey attribute to the class having the one (of a one-many relationship) relationship.Ideally your classes should be like this

    public partial class ContentArticleHOAsubdivision
{
    public int Id { get; set; }
    [ForeignKey("ContentArticleHOA")]
    public long ContentArticleId { get; set; }

    public virtual ContentArticleHOA ContentArticleHOA { get; set; }
    public virtual ICollection<SubdivisionHOA> SubdivisionsHOA { get; set; }
}

public partial class SubdivisionHOA
{
    [Key, ForeignKey("TopTierDivisionHOA")]
    public short Id { get; set; }
    public string Name { get; set; }

     [ForeignKey("ContentArticleHOAsubdivision")]
    public short ContentArticleHOAsubdivision{ get; set; }

    public virtual TopTierDivisionHOA TopTierDivisionHOA { get; set; }
}

Upvotes: 0

Marko Devcic
Marko Devcic

Reputation: 1101

Try this, add a property of the related entity type, in your case SubdivisionHOA, and add foreign key attribute to that property

public partial class ContentArticleHOAsubdivision
{

    public short SubdivisionHOAId { get; set; }

    [ForeignKey("SubdivisionsHOAId")]    
    public virtual SubdivisionHOA SubdivisionHOA {get;set;}

}

Upvotes: 1

Related Questions