Entity Framework 6 User Relationship Convention

I read this agreement documentation in Entity Framework 6. But it does not contain an agreement for relationships.

Suppose I have the following model:

[TablePrefix("mst")] public class Guru { public int Id { get; set; } public int? IdKotaLahir { get; set; } public virtual Kota KotaLahir { get; set; } } 

I want the IdKotaLahir property IdKotaLahir be the foreign key of the KotaLahir navigation KotaLahir . The foreign key name is "Id"+<NavigationPropertyName> . Is it possible to use the current version of the entity structure (EF 6 alpha 3)?

+2
c # entity-framework entity-framework-6
Mar 23 '13 at 19:13
source share
2 answers

Is this just one property, or do you need it in all directions (i.e. the whole model uses a convention where foreign key names are always "Id" + NavigationPropertyName)? If you only need a foreign key for a single object, you would be better off 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 user conventions to configure foreign key properties. Here is the usual 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 about this.

+2
Mar 23 '13 at 22:13
source share

In EF6, the accepted response convention no longer works because IConfigurationConvention is internal. A way to handle this type of script is to inherit from ForeignKeyDiscoveryConvention.

 public class MyForeignKeyDiscoveryConvention : ForeignKeyDiscoveryConvention { protected override bool MatchDependentKeyProperty(AssociationType associationType, AssociationEndMember dependentAssociationEnd, EdmProperty dependentProperty, EntityType principalEntityType, EdmProperty principalKeyProperty) { string navigationPropertyName = ((System.Reflection.PropertyInfo)dependentAssociationEnd.MetadataProperties.GetValue("ClrPropertyInfo", false).Value).Name; // The standard foreign key property to look for is NavigationProperty_PrimaryKeyName (eg "TableName_Id"). // Use the below line to remove that underscore. //return dependentProperty.Name == navigationPropertyName + principalKeyProperty.Name; // Use the following for the IdKotaLahir scenario return dependentProperty.Name == "Id" + navigationPropertyName; } } 
+2
May 5 '17 at 15:46
source share



All Articles