Question

I have been supplied a DB, and I need to get Code First set up for it. I think I'm mostly done, the problem that I'm running into right now is I want to change some of the foreign key names in the entities to make a little more sense.

Let's say I have two tables, Person and Location, that look like this:

Person
------
PersonId int not null (PK)
DefaultLocation int not null (FK)


Location
--------
LocationId int not null (PK)

For the location entity, I think I've got it:

public class Location
{
    [Key]
    public int LocationId { get; set; }

    [InverseProperty("DefaultLocation")]
    public List<Person> PeopleWithDefault { get; set; }
}

Now, what I want is to have 2 properties on my Person entity, a DefaultLocation navigation property, and a DefaultLocationId property for the foreign key. This is where I'm at right now:

public class Person
{
    [Key]
    public int PersonId { get; set; }

    [ForeignKey("Location")]
    [Column("DefaultLocation")]
    [Required]
    public int DefaultLocationId { get; set; }

    public virtual Location DefaultLocation { get; set; }
}

Which is throwing this bad boy:

The ForeignKeyAttribute on property 'DefaultLocationId' on type 'Person' is not valid. The navigation property 'Location' was not found on the dependent type 'Person'. The Name value should be a valid navigation property name.

So, that error makes perfect sense... I just have no idea how to fix it. I'm obviously missing an annotation somewhere, or using [ForeignKey] incorrectly. Can anyone help me out?

Was it helpful?

Solution

Change the string in the FK attribute to the name of the property, not the name of the type: [ForeignKey("DefaultLocation")]

OTHER TIPS

I also faced the similar issue. see my classes below

Author is the Parent Table

public class Author
    {
        [Key]
        public int AuthorID { get; set; }
        [Required]
        public string Name { get; set; }
    }

Book has the AuthorID as foreign key

public class Book
    {
        [Key]
        public int BookId { get; set; }
        [Required]
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string Genre { get; set; }
        public DateTime PublishDate { get; set; }
        public string Description { get; set; }
        public int AuthorID { get; set; }
        [ForeignKey("AuthorID")]
        public virtual Author Author { get; set; }
    }

i just updated my code and added virtual for below

[ForeignKey("AuthorID")]
 public virtual Author Author { get; set; }

so basically in book i have the same property from Author

public int AuthorID { get; set; }

and one more virtual property of type Author

[ForeignKey("AuthorID")]
 public virtual Author Author { get; set; }

Hope this will help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top