2010-01-07 22 views
1

我正在嘗試SharpArchitecture,並希望讓FluentNHibernate爲我的MVC網站生成我的數據庫模式。SharpArchitecture - FluentNHibernate模式生成?

我在哪裏做這件事有點失落。我可以通過在「Application_beginrequest」中的NHibernateInitializer.Instance().InitializeNHibernateOnce(InitializeNHibernateSession);之後的global.asax.cs文件中添加SchemaUpdate thingy來完成。 (如果我在調用之前放置它,SharpArch會拋出異常)。

這看起來不對,它聞起來很糟糕。這感覺就像我在Sharp架構中缺少一些基本的東西,它允許自動生成數據庫到我的數據庫(MSSQL2005)。或者我不是?如果沒有,請使用流利的nhibernate和夏普體系結構填寫架構生成的最佳實踐。

在此先感謝!

編輯:我可能會補充一點,我在SharpArch的Northwind示例項目中尋找,但是想讓FNHb生成模式。

回答

3

你不想在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!

我希望這有助於;我寫得很快,所以如果我把你弄糊塗了,讓我知道。

+0

謝謝託德!我開始考慮做一個單獨的控制檯應用程序來生成模式,但是在我的其他測試中這樣做似乎是個好主意。 感謝所有偉大的代碼示例,它們一定會有所幫助! – 2010-01-08 15:28:07