Entity Framework 6 - Code First: table schema from classes' namespace

entity-framework

Question

Does any know if one can set the table schema of code first classes based on the classes' namespace?

For example, every class in namespace Core.Foo would have a schema of Foo.

1
12
4/1/2016 2:44:08 PM

Accepted Answer

Well, you could specify the schema name using one of these two options:

  • Using Data Annotations:

    [Table("TableName","Foo")]
    public class Entity
    {
    }
    
  • Using Fluent Api:

    modelBuilder.Entity<Entity>().ToTable("TableName", "Foo");
    

Update

Digging more in this subject, I think what you looking for is a Custom Convention of EF:

public class CustomSchemaConvention : Convention
{
    public CustomSchemaConvention()
    {
        Types().Configure(c => c.ToTable(c.ClrType.Name, c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1)));
    }
}

Then, in your context, you need to override the OnModelCreating method to add the new convention:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Add(new CustomSchemaConvention());
}
28
3/18/2015 7:32:24 PM

Popular Answer

I will add one thing to what octavioccl provided. If you would like to preserve table name pluralization, you can use built-in pluralization service like this:

using System.Data.Entity.Infrastructure.DependencyResolution;
public class CustomSchemaConvention : Convention
{
    public CustomSchemaConvention()
    {
        var pluralizationService = DbConfiguration.DependencyResolver.GetService<IPluralizationService>();
        Types().Configure(c => c.ToTable(
            pluralizationService.Pluralize(c.ClrType.Name),
            c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1))
        );
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow