zeonic zeonic - 2 months ago 25
C# Question

Can't get property names working with foreign keys in Code First

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:

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

LocationId int not null (PK)

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

public class Location
public int LocationId { get; set; }

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
public int PersonId { get; set; }

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?


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