Last active
March 8, 2019 15:06
-
-
Save rexcfnghk/3a6becedb3e09819a4e0 to your computer and use it in GitHub Desktop.
Naming convention for Entity Framework to remove underscores in foreign key names in many-to-many relationships, improved upon SO answer: http://stackoverflow.com/a/18245172/465056
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
using System.Collections.Generic; | |
using System.Data.Entity.Core.Metadata.Edm; | |
using System.Data.Entity.Infrastructure; | |
using System.Data.Entity.ModelConfiguration.Conventions; | |
namespace EFTest.Entities.Conventions | |
{ | |
public class RemoveUnderscoreForeignKeyNamingConvention : IStoreModelConvention<AssociationType> | |
{ | |
public void Apply(AssociationType item, DbModel model) | |
{ | |
if (!item.IsForeignKey) | |
{ | |
return; | |
} | |
ReferentialConstraint constraint = item.Constraint; | |
ICollection<EdmProperty> fromProperties = constraint.FromProperties; | |
ICollection<EdmProperty> toProperties = constraint.ToProperties; | |
if (DoPropertiesHaveDefaultNames(fromProperties, toProperties)) | |
{ | |
NormalizeForeignKeyProperties(fromProperties); | |
} | |
if (DoPropertiesHaveDefaultNames(toProperties, fromProperties)) | |
{ | |
NormalizeForeignKeyProperties(toProperties); | |
} | |
} | |
private static bool DoPropertiesHaveDefaultNames(ICollection<EdmProperty> properties, | |
ICollection<EdmProperty> otherEndProperties) | |
{ | |
if (properties.Count != otherEndProperties.Count) | |
{ | |
return false; | |
} | |
using (IEnumerator<EdmProperty> propertiesEnumerator = properties.GetEnumerator()) | |
using (IEnumerator<EdmProperty> otherEndPropertiesEnumerator = otherEndProperties.GetEnumerator()) | |
{ | |
while (propertiesEnumerator.MoveNext() && otherEndPropertiesEnumerator.MoveNext()) | |
{ | |
if (!propertiesEnumerator.Current.Name.EndsWith("_" + otherEndPropertiesEnumerator.Current.Name)) | |
{ | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
private static void NormalizeForeignKeyProperties(IEnumerable<EdmProperty> properties) | |
{ | |
foreach (EdmProperty edmProperty in properties) | |
{ | |
int underscoreIndex = edmProperty.Name.IndexOf('_'); | |
if (underscoreIndex > 0) | |
{ | |
edmProperty.Name = edmProperty.Name.Remove(underscoreIndex, 1); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment