上一篇文章中,我們分析了系統的兩個實體類,並且給出了對應的實體XML。今天我們來看看如何根據 這個XML進行代碼生成。
1: <?xml version="1.0" encoding="utf-8" ?> 2: <Entities xmlns="http://it.ouc.edu.cn/EntityDescription/V2"> 3: <Entity title="日志" name="Blog" module="Blogs"> 4: <Item title="標題" name="Title" type="text" require="true"/> 5: <Item title="內容" name="Content" type="longtext" require="false"/> 6: <Item title="所屬分類" name="BlogClass" type="entity" entityName="BlogClass" require="false"/> 7: <Item title="創建時間" name="CreateDateTime" type="datetime" require="true"/> 8: <Item title="更新時間" name="UpdateDateTime" type="datetime" require="true"/> 9: </Entity> 10: <Entity title="日志分類" name="BlogClass" module="Blogs"> 11: <Item title="名稱" name="Name" type="text" require="true"/> 12: <Item title="描述" name="Description" type="text" require="false"/> 13: </Entity> 14: </Entities>
這裡我們主要是生成兩種最重要的代碼,一是數據庫的建庫腳本,二是實體的CS類。
我們使用測試來驅動代碼生成,在項目DongBlog.Test中添加一個新的單元測試:Util.cs。對應的代 碼如下:
1: using ... 12: 13: namespace DongBlog.Test 14: { 15: /// <summary> 16: /// 數據庫相關的工具方法 17: /// </summary> 18: [TestClass] 19: public class DatabaseUtil 20: { 21: /// <summary> 22: /// 構造建庫腳本 23: /// </summary> 24: [TestMethod, Description("構造建庫腳本")] 25: public void Util_CreateDatabaseScript() 26: { 27: var entities = getEntities(); 28: string sqlText = MsSqlServerScriptBuilder.getSqlScript(entities); 29: 30: Debug.WriteLine(""); 31: Debug.WriteLine("The following is the database creating script:"); 32: Debug.WriteLine("=============================彪悍的分割線 =============================================================================="); 33: Debug.WriteLine(""); 34: Debug.WriteLine(""); 35: Debug.WriteLine(sqlText); 36: Debug.WriteLine(""); 37: Debug.WriteLine(""); 38: Debug.WriteLine("=============================又見彪悍的分割線 =========================================================================="); 39: } 40: 41: private Entity[] getEntities() 42: { 43: XmlDocument document = new XmlDocument(); 44: document.Load(Gobal.EntityXmlFileName); 45: return EntityXmlParser.ParseXml(document); 46: } 47: } 48: }