Created
August 16, 2018 18:22
-
-
Save Citillara/ef6125ee990d4cc0d3939a85508381f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Provides a convention for fixing the independent association (IA) foreign key column names. (prevents EF from adding _Id) | |
/// </summary> | |
public class ForeignKeyNamingConvention : IStoreModelConvention<AssociationType> | |
{ | |
public void Apply(AssociationType association, DbModel model) | |
{ | |
// Identify a ForeignKey properties (including IAs) | |
if (association.IsForeignKey) | |
{ | |
// rename FK columns | |
var constraint = association.Constraint; | |
if (DoPropertiesHaveDefaultNames(constraint.FromProperties, constraint.ToRole.Name, constraint.ToProperties)) | |
{ | |
NormalizeForeignKeyProperties(constraint.FromProperties); | |
} | |
if (DoPropertiesHaveDefaultNames(constraint.ToProperties, constraint.FromRole.Name, constraint.FromProperties)) | |
{ | |
NormalizeForeignKeyProperties(constraint.ToProperties); | |
} | |
} | |
} | |
private bool DoPropertiesHaveDefaultNames(ReadOnlyMetadataCollection<EdmProperty> properties, string roleName, ReadOnlyMetadataCollection<EdmProperty> otherEndProperties) | |
{ | |
if (properties.Count != otherEndProperties.Count) | |
{ | |
return false; | |
} | |
for (int i = 0; i < properties.Count; ++i) | |
{ | |
if (!properties[i].Name.EndsWith("_" + otherEndProperties[i].Name)) | |
{ | |
return false; | |
} | |
} | |
return true; | |
} | |
private void NormalizeForeignKeyProperties(ReadOnlyMetadataCollection<EdmProperty> properties) | |
{ | |
for (int i = 0; i < properties.Count; ++i) | |
{ | |
string defaultPropertyName = properties[i].Name; | |
int ichUnderscore = defaultPropertyName.IndexOf('_'); | |
if (ichUnderscore <= 0) | |
{ | |
continue; | |
} | |
string navigationPropertyName = defaultPropertyName.Substring(0, ichUnderscore); | |
string targetKey = defaultPropertyName.Substring(ichUnderscore + 1); | |
string newPropertyName; | |
if (targetKey.StartsWith(navigationPropertyName)) | |
{ | |
newPropertyName = targetKey; | |
} | |
else | |
{ | |
newPropertyName = navigationPropertyName + targetKey; | |
} | |
properties[i].Name = newPropertyName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment