你不想在Application_BeginRequest中做到這一點。
要自動生成DDL,你應該做的是在你的TDD類中進行。創建一個特殊的類,您可以在需要爲開發數據庫生成DDL時手動調用該類。
喜歡的東西:
private static void CreateDatabaseFromFluentNHibernateMappings()
{
var mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies();
SchemaExport schema = new SchemaExport(NHibernateSession.Init(new SimpleSessionStorage(), mappingAssemblies, NHIBERNATE_CFG_XML));
schema.Execute(true, true, false);
}
這將生成並執行基於你的映射在你的NHibernate配置文件指定該數據庫(在NHIBERNATE_CFG_XML)的DDL。數據庫儘管爲空,但應該已經存在。
你也可以創建你的類的另一種方法,你在你添加新的實體,屬性的情況下開發可更新發展數據庫的架構等
private static void UpdateExistingDatabaseFromFluentNHibernateMappings()
{
var mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies();
SchemaUpdate schema = new SchemaUpdate(NHibernateSession.Init(new SimpleSessionStorage(), mappingAssemblies, NHIBERNATE_CFG_XML));
schema.Execute(true, true);
}
這將更新現有的數據庫與您在FNH中所做的更改不會破壞現有數據庫。非常有用,尤其是當您可能已經在數據庫中存在測試數據時。
最後,您可以使用NDbUnit根據項目和SCM下的XML中定義的測試數據預加載數據庫。當你有一個團隊在同一個數據庫上工作,並且你想用數據預先加載時,這是非常棒的,因此每個人都用相同的空白頁開始。
使用NDbUnit:
private static void LoadTheTestDataintoDb()
{
const string connectionstring = // your connection string to your db
NDbUnit.Core.INDbUnitTest sqlDb = new NDbUnit.Core.SqlClient.SqlDbUnitTest(connectionstring);
sqlDb.ReadXmlSchema(/* your XML schema file defining your database (XSD) */);
sqlDb.ReadXml(/* Your XML file that has your test data in it (XML) */);
// Delete all from existing db and then load test data allowing for identity inserts
sqlDb.PerformDbOperation(NDbUnit.Core.DbOperationFlag.CleanInsertIdentity);
}
這需要你使用NDbUnit。感謝Stephen Bohlen!
我希望這有助於;我寫得很快,所以如果我把你弄糊塗了,讓我知道。
謝謝託德!我開始考慮做一個單獨的控制檯應用程序來生成模式,但是在我的其他測試中這樣做似乎是個好主意。 感謝所有偉大的代碼示例,它們一定會有所幫助! – 2010-01-08 15:28:07