zeonic zeonic - 27 days ago 12
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:

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?

Answer

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