使用Castle ActiveRecord构建数据库模式时,是否可以排除某些表

时间:2011-08-25 02:13:20

标签: nhibernate activerecord nhibernate-mapping castle-activerecord

我们使用Castle ActiveRecord作为NHibernate之上的辅助层。要生成我们的数据库,我们使用:

ActiveRecordStarter.CreateSchema();

要生成用于构建数据库的sql,我们使用:

ActiveRecordStarter.GenerateCreationScripts(filename);

他们的工作就像一个魅力。但是,我们有时不希望为每个实体生成一个表。我相信nhibernate有一种从模式构建中排除某些表的机制(参见here) - 有谁知道ActiveRecord是否可以做同样的事情?

1 个答案:

答案 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));
}

一个黑客,但它确实起作用。