0

我們使用Castle ActiveRecord作爲NHibernate頂層的幫助器層。要生成我們的數據庫中,我們使用:我可以使用Castle ActiveRecord構建我的數據庫模式時排除某些表格

ActiveRecordStarter.CreateSchema(); 

來產生我們用於構建我們的數據庫的SQL:

ActiveRecordStarter.GenerateCreationScripts(filename); 

他們的工作就像一個魅力。但是我們有時不想爲每個實體生成一個表格。我相信nhibernate有一個從模式構建中排除某些表的機制(請參閱here) - 有誰知道ActiveRecord是否可以做同樣的事情?

+0

我不這麼認爲。 –

回答

0

留給後人,這是我落得這樣做:

1)抓起NHibernate的SchemaExporter源代碼,並改名爲類「OurSchemaExporter」。

2)增加了一個新的構造:

public OurSchemaExporter(Configuration cfg, Func<string, bool> shouldScriptBeIncluded) 
     : this(cfg, cfg.Properties) 
    { 
     this.shouldScriptBeIncluded = shouldScriptBeIncluded ?? (s => true); 
    } 

3)改性initialize方法叫出以找出一個腳本是否應包含:

private void Initialize() 
    { 
     if (this.wasInitialized) 
      return; 
     if (PropertiesHelper.GetString("hbm2ddl.keywords", this.configProperties, "not-defined").ToLowerInvariant() == Hbm2DDLKeyWords.AutoQuote) 
      SchemaMetadataUpdater.QuoteTableAndColumns(this.cfg); 
     this.dialect = Dialect.GetDialect(this.configProperties); 
     this.dropSQL = this.cfg.GenerateDropSchemaScript(this.dialect); 
     this.createSQL = this.cfg.GenerateSchemaCreationScript(this.dialect); 

     // ** our modification to exclude certain scripts ** 
     this.dropSQL = new string[0]; // we handle the drops ourselves, as NH doesn't know the names of all our FKs 
     this.createSQL = this.createSQL.Where(s => shouldScriptBeIncluded(s)).ToArray(); 

     this.formatter = (PropertiesHelper.GetBoolean("format_sql", this.configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter; 
     this.wasInitialized = true; 
    } 

4)當使用OurSchemaExporter,通過查看每個SQL創建腳本的內容來檢查是否要包含某些表:

var ourSchemaExport = new TpsSchemaExporter(configuration, ShouldScriptBeIncluded); 

... 

private bool ShouldScriptBeIncluded(string script) 
{ 
    return !tablesToSkip.Any(t => ShouldSkip(script, t)); 
} 

private static bool ShouldSkip(string script, string tableName) 
{ 
    string s = script.ToLower(); 
    string t = tableName.ToLower(); 
    return 
    s.Contains(string.Format("create table dbo.{0} ", t)) 
    || s.Contains(string.Format("alter table dbo.{0} ", t)) 
    || s.EndsWith(string.Format("drop table dbo.{0}", t)); 
} 

黑客,但它做的工作。

+0

你應該接受你自己的答案。 – rbellamy

相關問題