3

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?

Community
  • 1
  • 1
Johan B
  • 890
  • 3
  • 23
  • 39

2 Answers2

4

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";
}
bricelam
  • 28,825
  • 9
  • 92
  • 117
  • Awesome, this works perfectly. Changes the table names from Idenity too but I suppose that's just an easy thing to change in that loop. Thanks! – Johan B Dec 12 '15 at 22:12
3

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.

JotaBe
  • 38,030
  • 8
  • 98
  • 117
  • Yes, I see. Well then I suppose we could just do it manually by using the `[Table("Namespace_Foo")]` attribute above the classes, at least for the time being. – Johan B Dec 09 '15 at 13:27