Is it just one property or you need this across the board (i.e. the whole model is using a convention where foreign key names are always "Id" + NavigationPropertyName)? If you just want the foreign key for a single entity you will be better off just using the ForeignKey
attribute:
public class Guru
{
public int Id { get; set; }
public int? IdKotaLahir { get; set; }
[ForeignKey("IdKotaLahir")]
public virtual Kota KotaLahir { get; set; }
}
This will work for both EF5 and EF6. In EF6 you can use custom conventions to configure foreign key properties. Here is custom convention I came up with:
public class NavigationPropertyConfigurationConvention
: IConfigurationConvention<PropertyInfo, NavigationPropertyConfiguration>
{
public void Apply(
PropertyInfo propertyInfo, Func<NavigationPropertyConfiguration> configuration)
{
var foreignKeyProperty =
propertyInfo.DeclaringType.GetProperty("Id" + propertyInfo.Name);
if (foreignKeyProperty != null && configuration().Constraint == null)
{
var fkConstraint = new ForeignKeyConstraintConfiguration();
fkConstraint.AddColumn(foreignKeyProperty);
configuration().Constraint = fkConstraint;
}
}
}
I also wrote a more detailed blog post on this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…