【发布时间】:2013-03-06 16:14:09
【问题描述】:
我制作了一个小型软件工具,允许我显示或运行从 NHibernate 生成的 SQL。我这样做是因为hbm2ddl.auto is not recommended for production。
我有一个问题:当我生成 SQL 时,我总是把臭名昭著的 Index 列不加引号,因为我需要 .AsList() 映射。这会阻止我运行 SQL。
理论上,如果我有一个 NHibernate 的 XML 配置,我可以使用 hbm2ddl.keywords 标签,但不幸的是,由于我的工具被设计为支持多种环境的 DBA 工具,我必须使用编程方法。
我的方法(冗余)如下:
private static Configuration BuildNHConfig(string connectionString, DbType dbType, out Dialect requiredDialect)
{
IPersistenceConfigurer persistenceConfigurer;
switch (dbType)
{
case DbType.MySQL:
{
persistenceConfigurer =
MySQLConfiguration
.Standard
.Dialect<MySQL5Dialect>()
.Driver<MySqlDataDriver>()
.FormatSql()
.ShowSql()
.ConnectionString(connectionString);
requiredDialect = new MySQL5Dialect();
break;
}
case DbType.MsSqlAzure:
{
persistenceConfigurer = MsSqlConfiguration.MsSql2008
.Dialect<MsSqlAzure2008Dialect>()
.Driver<SqlClientDriver>()
.FormatSql()
.ShowSql()
.ConnectionString(connectionString);
requiredDialect = new MsSqlAzure2008Dialect();
break;
}
default:
{
throw new NotImplementedException();
}
}
FluentConfiguration fc = Fluently.Configure()
.Database(persistenceConfigurer)
.ExposeConfiguration(
cfg => cfg.SetProperty("hbm2ddl.keywords", "keywords")
.SetProperty("hbm2ddl.auto", "none"))
.Mappings(
m => m.FluentMappings.AddFromAssemblyOf<NHibernateFactory>());
Configuration ret = fc.BuildConfiguration();
SchemaMetadataUpdater.QuoteTableAndColumns(ret);
return ret;
}
...
public static void GenerateSql(MainWindowViewModel viewModel)
{
Dialect requiredDialect;
Configuration cfg = BuildNHConfig(viewModel.ConnectionString, viewModel.DbType.Value, out requiredDialect);
StringBuilder sqlBuilder = new StringBuilder();
foreach (string sqlLine in cfg.GenerateSchemaCreationScript(requiredDialect))
sqlBuilder.AppendLine(sqlLine);
viewModel.Sql = sqlBuilder.ToString();
}
说明:当我想将ViewModel 的SQL 设置为在TextBox 上显示时(是的,这是WPF),我使用ViewModel 中给出的连接字符串以编程方式初始化配置,并相应地选择方言/提供程序。当我FluentlyConfigureNHibernate 时,我都设置了hbm2ddl.keywords(尝试了auto-quote 和keywords,这是默认设置),并且在this blog post 之后,我也使用SchemaMetadataUpdater。
结果是我总是看到像
这样的 SQLcreate table `OrderHistoryEvent` (Id BIGINT NOT NULL AUTO_INCREMENT, EventType VARCHAR(255) not null, EventTime DATETIME not null, EntityType VARCHAR(255), Comments VARCHAR(255), Order_id VARCHAR(255), Index INTEGER, primary key (Id))
没有引用有罪的Index 列。
问题是:给定 NHibernate 的编程和流畅配置,我如何告诉 NHibernate 引用GenerateSchemaCreationScript 导出的 SQL 中的任何保留字?
【问题讨论】:
-
我在考虑使用约定。任何名为 Index 的列都被重命名为...例如 ListIndex
标签: mysql sql nhibernate fluent-nhibernate quotes