How to map Entity Framework Code-First to a single SQL Server schema?

I am creating an Entity Framework Code-First model to perform special queries on a SQL Server database. I do not include tables or views from the "dbo" schema in my EF model; instead, I only use tables / views from the "model" schema in my database. I have duplicate object names in my database that are separated only by a schema (for example, "dbo.Child" and "model.Child").

Is there one line that I can specify in a DbContext that will essentially “map all objects in this context to a“ model schema ”? I know that I can match each entity with a corresponding schema (see below), but I would like to avoid re-excluding all objects in my database.

This is what I know I can do:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{       
    modelBuilder.Entity<Child>().ToTable("Child", "model");
    modelBuilder.Entity<Referral>().ToTable("Referral", "model");
    // 100 lines later...
    modelBuilder.Entity<Exit>().ToTable("Exit", "model");
}

This is what I would like to do:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{       
    modelBuilder.Conventions.Add(new MapAllEntitiesToSchemaConvention("model"));
}
+3
source share
1 answer

I still couldn’t find this out of the box in EF 4.2, but I need all my entities to be in a different scheme, so I hacked into this while trying to save DRYer stuff. It uses the same basic pluralization mechanism as EF, and the overrides are that entities must specify a table name.

Link to required System.Data.Entity.Design.

public class BaseConfiguration<TEntityType> : EntityTypeConfiguration<TEntityType> where TEntityType : class
{
    private readonly static PluralizationService ps = PluralizationService.CreateService(new CultureInfo("en-US"));

    public BaseConfiguration() : this(ps.Pluralize(typeof(TEntityType).Name)) { }
    public BaseConfiguration(string tableName) : this(tableName, MyContext.Schema) { }
    public BaseConfiguration(string tableName, string schemaName)
    {
        ToTable(tableName, schemaName);
    }
}

MyContext, :

public class MyContext : DbContext
{
    public const string Schema = "my";

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new SnapshotConfiguration());
    }
}

:

public class SnapshotConfiguration : BaseConfiguration<Snapshot>
{
    ...
}

: - , , .

+2

All Articles