我製作了一個小軟件工具,允許我顯示或運行從NHibernate生成的SQL。我做這個是因爲hbm2ddl.auto is not recommended for production。啓用hbm2ddl.keywords =在Fluent NHibernate中自動引用
我有一個問題:當我生成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語句顯示一個文本框(是的,這是WPF)我編程方式與初始化配置連接字符串在ViewModel
中給出,並相應地選擇方言/提供者。當我Fluently
Configure
NHibernate我都設置hbm2ddl.keywords
(同時嘗試auto-quote
和keywords
,這是默認值),並且,在this blog post之後,我也使用SchemaMetadataUpdater
。
的結果是,我總是帶有SQL像
create 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 – 2013-03-18 10:53:25