2011-06-10 18 views
3

我正在創建一個實體框架代碼優先模型來執行鍼對SQL Server數據庫的臨時查詢。我在EF模型中不包含任何來自「dbo」模式的表/視圖;相反,我只在我的數據庫中包含來自「模型」模式的表/視圖。我的數據庫中確實有重複名稱的對象,這些對象僅由模式(例如「dbo.Child」和「model.Child」)分隔。如何將實體框架代碼優先模型映射到單個SQL Server模式?

是否有一行我可以在DbContext中指定,本質上將「將此上下文中的所有實體映射到'模型'模式」?我知道我可以將每個實體映射到適當的模式(請參閱下文),但我想避免再次列出數據庫中的每個實體。

這是我知道我可以做:

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"); 
} 

這是我想做什麼:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{  
    modelBuilder.Conventions.Add(new MapAllEntitiesToSchemaConvention("model")); 
} 

回答

2

我找不到反正做這個開箱在EF 4.2中,但我需要我所有的實體都處於不同的模式中,所以我爲了保留DRYER而進行了黑客攻擊。它使用與EF相同的基礎多元化引擎,並且覆蓋是incase實體需要指定表名。

需要參考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> 
{ 
    ... 
} 

警告:我還需要配置的每個實體我想要在正確的模式 - 但它的jist可以通過其他地方。

相關問題