I am creating an Entity Framework Code-First model to execute ad-hoc queries against a SQL Server database. I am not including any tables/views from the "dbo" schema in my EF model; instead I am only including tables/views from the "model" schema in my database. I do have duplicate names of obj开发者_StackOverflow中文版ects in my database that are separated only by schema (e.g. "dbo.Child" and "model.Child").
Is there one line I can specify in the DbContext that will say in essence "map all entities in this context to the 'model' schema"? I know that I can map each entity to the proper schema (see below), but I'd like to avoid listing out every entity in my database again.
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'd like to do:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new MapAllEntitiesToSchemaConvention("model"));
}
I couldn't find anyway to do this out of the box in EF 4.2, but I needed all my entities to be in a different schema so I hacked this up in an attempt to keep things DRYer. It uses the same underlying pluralization engine as EF, and the overrides are there incase entities need to specify the table name.
A reference to System.Data.Entity.Design
is needed.
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);
}
}
I define the schema name via a constant string in MyContext
, ie:
public class MyContext : DbContext
{
public const string Schema = "my";
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new SnapshotConfiguration());
}
}
And my entities configurations look like:
public class SnapshotConfiguration : BaseConfiguration<Snapshot>
{
...
}
Caveat: I still need configuration's for each entity I want in the correct schema - but the jist of it could be adopted elsewhere.
精彩评论