12

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.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
Robbie
  • 458
  • 1
  • 3
  • 12

3 Answers3

32

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());
}
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • Very thorough answer. Thank you. – Robbie Mar 18 '15 at 19:34
  • 1
    Keep in mind that this disables the default pluralization for table names. If that's not what you want, you need to pluralize them again. I provided sample code below. – mco Dec 02 '16 at 13:43
  • 1
    in .Net Core you need to explicitly state Schema e.g. [Table("TableName",Schema = "Foo")] – Shaheen K May 31 '18 at 14:49
8

In EF 6.2 or EF Core, use the Schema property to specify the schema name for a Db table as shown below:

[Table("TableName", Schema = "Foo")]
public class Entity
{
    //Properties
}

Details Here

sebu
  • 2,824
  • 1
  • 30
  • 45
5

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))
        );
    }
}
mco
  • 159
  • 1
  • 7