Last active
December 10, 2015 04:42
-
-
Save dataneek/b82641fc1b0b97aa9b89 to your computer and use it in GitHub Desktop.
Entity Framework convention from http://stackoverflow.com/questions/15684555/how-do-i-remove-underscore-of-foreign-key-fields-in-code-first-by-convention
This file contains 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; | |
using System.Data.Entity.Core.Metadata.Edm; | |
using System.Data.Entity.Infrastructure; | |
using System.Data.Entity.ModelConfiguration.Conventions; | |
//# Rename code first foreign keys from [{Table}_{ColumnId}] to [{ColumnId}]. | |
public class ForeignKeyNamingConvention : IStoreModelConvention<AssociationType> | |
{ | |
public void Apply(AssociationType association, DbModel model) | |
{ | |
if (association.IsForeignKey) | |
{ | |
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) | |
{ | |
int underscoreIndex = properties[i].Name.IndexOf('_'); | |
if (underscoreIndex > 0) | |
{ | |
properties[i].Name = properties[i].Name.Split("_".ToCharArray())[0] + "Id"; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment