Paul Michaels
Paul Michaels

Reputation: 16705

Working with Schemas in EF Code First Migrations

I suppose this question is a cosmetic one; when you initially create an EF migration, it puts the schema in by default; for example:

public override void Up()
{            
    DropPrimaryKey("dbo.MyTable");

    AddPrimaryKey("dbo.MyTable", "NewField");

This seems fine, unit you see the key name that it generates as a result (it has dbo in the key name).

I realise that one way around this is to specify the key name directly. Are there any other options, for example, can the schema be specified for a block, but not included in the specific modifications? For example:

public override void Up()
{            
    UseSchema("dbo");
    DropPrimaryKey("MyTable");

    AddPrimaryKey("MyTable", "NewField");

I realise that you can simply omit the schema name; i.e., this will work:

public override void Up()
{            
    DropPrimaryKey("MyTable");

    AddPrimaryKey("MyTable", "NewField");

But how would I then deal with a situation where there were more than a single schema?

Upvotes: 3

Views: 4884

Answers (1)

sramekpete
sramekpete

Reputation: 3208

You can specify default schema using HasDefaultSchema method on DbModelBuilder class instance.

modelBuilder.HasDefaultSchema("schemaName");

You can also set schema for each entity using ToTable method on EntityTypeConfiguration<TEntityType> class instance. Which will generate migration scripts with provided schema for desired entity/ies.

modelBuilder.Entity<TEntity>().ToTable("tableName", "schemaName")

You can also use Table attribute to set schema for entity.

[Table("tableName","schemaName")]

Or you can write your own custom convention

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

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Add(new CustomSchemaConvention());
}

Related links:

DbModelBuilder.HasDefaultSchema Method

EntityTypeConfiguration.ToTable Method

TableAttribute Class

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

Entity Framework Custom Code First Conventions (EF6 onwards)

Upvotes: 4

Related Questions