Global table prefix with Entity Framework 7 (rc1)

asp.net-core c# entity-framework entity-framework-core

Question

We're using the RC1 release of ASP.NET 5 with the new Entity Framework 7 and I'd like to have table names in the database to be prefixed with the name of the namespace in which the model lives.

I know how to do this with in the previous version of Entity Framework (thanks to this SO question) but I can't figure out how to do the same in the new version. I went through the docs, Googled it and poked my head in the source code, to no avail.

What I do in EF6:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Types().Configure(entity => entity.ToTable($"{entity.ClrType.Namespace?.Replace('.', '-')}_{entity.ClrType.Name}s"));

    base.OnModelCreating(modelBuilder);
}

How can I do the same with EF7? Is this one of the things that aren't in there yet maybe?

Accepted Answer

Do it at the end of OnModelCreating by manipulating the model directly:

foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    entity.Relational().TableName =
        $"{entity.ClrType.Namespace?.Replace('.', '-')}_{entity.ClrType.Name}s";
}

Popular Answer

As of today, Dic, 9th, 2015, the EF7 custom conventions issue is still open:

https://github.com/aspnet/EntityFramework/issues/214

If you visit that link, you can drill into more details.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why