2011-04-05 34 views
1

我有一個問題,可能很簡單,但我找不到任何關於它的問題。EF代碼第一和Db所有者

我在傳統數據庫上使用EF 4.1 Code First。在我們的開發環境中,所有表都在「dbo」所有者之下,但在生產中有一些在另一個用戶之下,比如說「myuser」。

我使用方法「ToTable」來映射我的對象,該方法僅指定沒有所有者的表名稱。這樣,EF自動嘗試繼續[dbo]。[TableName]並在生產中拋出無效的對象名稱錯誤,因爲表爲[myuser]。[TableName]

有沒有辦法告訴EF忽略數據庫所有者何時映射表?我無法在生產環境中更改所有者,並且我無法將其他原因複製到我們的開發數據庫中的生產配置。

謝謝。

回答

1

您可以在運行時設置架構。

public class YourDbContext : DbContext 
{ 
    public IDbSet<SomeObject> SomeObjects { get; set; } 
    public IDbSet<SomeOtherObject> SomeOtherObjects { get; set; } 
    public IDbSet<YetAnotherObject> YetMoreObjects { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Configurations.Add(new RuntimeSchemaConfiguration<SomeObject>()); 
     modelBuilder.Configurations.Add(new RuntimeSchemaConfiguration<SomeOtherObject>()); 
     modelBuilder.Configurations.Add(new RuntimeSchemaConfiguration<YetAnotherObject>()); 
    } 

    private class RuntimeSchemaConfiguration<T> : EntityTypeConfiguration<T> 
     where T : class 
    { 
     public RuntimeSchemaConfiguration() 
     { 
      // Rename the schema based on a string 
      // from a config file or other source 
      var schemaName = GetSchemaNameFromConfigFile(); 
      ToTable(typeof(T).Name, schemaName); 
     } 
    } 
} 
+0

看起來很有趣,我明天再看看,我會告訴你的。謝謝。 – 2011-04-05 16:08:44