I would like to know what rules Entity Framework follows in regards to the naming/generation of navigation properties. I have observed several scenarios which don't seem to make sense so I was wondering if anyone knows exactly how these work.
Scenario 1:
public class Post
{
public int Id { get; set; }
public User Author { get; set; }
}
Generates
ie. by default navigation properties generate FKs named [PropertyName]_Id
Scenario 2:
It makes sense that if EF generates properties such of the format [PropertyName]_Id when you manually specify a FK Id it will follow the same rules however:
public class Post
{
public int Id { get; set; }
public int? Author_Id { get; set; }
public User Author { get; set; }
}
Generates
As you can see this doesn't automatically register as a nav property.
Scenario 3:
If it doesn't work for Scenario 2 why does it work for an alternate naming convention?
public class Post
{
public int Id { get; set; }
public int? AuthorId { get; set; }
public User Author { get; set; }
}
Generates
What are the rules around navigation property detection and generation?
A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data.
A navigation property is one that the database provider being used cannot map to a primitive (or scalar) type. The following code depicts the model representation of the database example above: public class Author. { public int AuthorId { get; set; }
An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.
You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.
That is expected behavior and it is based on two different conventions based by EF
NameOfNavigationProperty_NameOfRelatedPK
This convention follows traditional database naming.NameOfNavigationPropertyNameOfRelatedPK
provided by NavigationPropertyNameForeignKeyDiscoveryConvention
NameOfRelatedTypeNameOfItsPK
provided by TypeNameForeignKeyDiscoveryConvention
NameOfRelatedPK
provided by PrimaryKeyNameForeignKeyDiscoveryConvention
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With