Cannot get property names that work with foreign keys in Code First

I was provided with a DB, and I need to install Code First for it. I think Iā€™m basically done, the problem that I am facing right now is that I want to change some foreign key names in essence in order to make a little more sense.

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

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

For a location object, I think I have this:

 public class Location { [Key] public int LocationId { get; set; } [InverseProperty("DefaultLocation")] public List<Person> PeopleWithDefault { get; set; } } 

Now I want to have 2 properties in the Person object, the navigationLocationLocation property and the DefaultLocationId property for the foreign key. This is where I am 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; } } 

What casts this bad boy:

ForeignKeyAttribute in the 'DefaultLocationId' property for type 'Person' is not valid. The navigation property "Location" was not found on the dependent type "Face". Name must be a valid name for the navigation property.

So this error makes sense ... I just don't know how to fix it. I am clearly missing the annotation or wrong [ForeignKey]. Can anyone help me out?

0
source share
2 answers

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

+1
source

I also ran into a similar problem. see my classes below

The author is the parent table

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

Book has 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 a virtual below

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

so basically in the book I have the same property from the author

 public int AuthorID { get; set; } 

and another virtual property of type Author

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

Hope this helps.

0
source

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


All Articles