Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Last active August 29, 2015 14:12
Show Gist options
  • Save MrAntix/56117f53b7f78e915503 to your computer and use it in GitHub Desktop.
Save MrAntix/56117f53b7f78e915503 to your computer and use it in GitHub Desktop.
I like my data models to have 'Data' as a suffix to make it easy to see that they are data models e.g. 'PersonData', but when I use EF this means that I get table names like 'UserDatas' or 'PersonDatas'. This EF Convention removes the Data suffix and still applies the pluralisation you expect
public class DataTableNameConvention :
Convention
{
public DataTableNameConvention(
IPluralizationService pluralizationService,
IDictionary<string, string> explicitNames)
{
Types().Configure(
c => c.ToTable(
GetName(c.ClrType, pluralizationService, explicitNames))
);
}
static string GetName(
Type type,
IPluralizationService pluralizationService,
IDictionary<string, string> explicitNames)
{
if (explicitNames.ContainsKey(type.Name))
return explicitNames[type.Name];
return pluralizationService
.Pluralize(type.Name.TrimEnd("Data"));
}
}
public static class StringExtensions
{
public static string TrimEnd(
this string value, string trimString,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (string.IsNullOrEmpty(value)
|| string.IsNullOrEmpty(trimString)) return value;
var lastIndex = value.Length;
int index;
while ((index = value.LastIndexOf(trimString, lastIndex, comparisonType)) != -1)
lastIndex = index;
return lastIndex != value.Length
? value.Substring(0, lastIndex)
: value;
}
}
@MrAntix
Copy link
Author

MrAntix commented Dec 31, 2014

usage:

public class DataContext :
    DbContext
{
    ...

    protected override void OnModelCreating(
        DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations
            .AddFromAssembly(GetType().Assembly);

        modelBuilder.Conventions
            .Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions
            .Add(new DataTableNameConvention(
                DbConfiguration.DependencyResolver
                    .GetService<IPluralizationService>(),
                new Dictionary<string, string>
                {
                    {"ATOData", "ATOs"}  // special cases
                })
            );
    }
}

You can pass in special cases, as above, where the pluralisation gets it wrong, otherwise 'ATO' acronym gets pluralised to 'ATOes'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment