自動生成Info類的另外一個重要的原因在于,在一般的情況下,這些Info類沒有可能一次就完全确定下來而不再修改,有了這個工具後,如果資料庫結構有修改,則不必手工去更改代碼,隻需要重新運作一個Info類的代碼生成器即可。
為了讓Info類适合一些邏輯要求,本Info類代碼生成器需要手工進行一些必要的配置。如:一個Table中有DepartmentId字段,在一般情況下也需要将DepartmentName加到Info類中;一個Table有詳細記錄清單,則一般情況下也應該在該Info類中加一個IList類型的容納記錄清單的字段等。
這些配置有些情況下是無法用代碼自動完成的,是以必須手工配置。不過好在配置也并不複雜,而且一旦配置,後續就可以重複使用。其配置舉例如下:
1 <?xml version="1.0" encoding="utf-8" ?>
2 <root>
3 <tables>
4 <item name="Department">
5 <associations>
6 <item name="Departments" from="Department" alias="parent" source="DepartmentParent" nullable="true" delete="true" />
7 </associations>
8 </item>
9 <item name="Employee">
10 <additions>
11 <item name="DepartmentName" from="Department" source="DepartmentId" target="DepartmentId" />
12 <item name="PositionName" from="Position" source="PositionId" target="PositionId" />
13 <item name="EmployeeName" alias="ManagerName" table="Manager" from="Employee" source="EmployeeManager" target="EmployeeId" />
14 </additions>
15 </item>
16 </tables>
17 <removes>
18 <item name="Table" />
19 </removes>
20 </root>
對于該Table已經存在的字段來說,則不用進行任何配置,我們需要配置的,隻是一些“異常”的字段。如附加字段(置于additions辨別下)、關聯記錄(置于associations辨別下)等。
下面列舉出主體部分的代碼。其中處理較麻煩的部分在于有些字段可以為空,是以需要采用Nullable<>這樣的範型類型。
1 for (int i = 0; i < columns.Count; i++)
2 {
3 strContentes = strContentes + " [DataMember]" + "\n";
4
5 if (islinqs[i].ToString() == "True")
6 {
7 strContentes += string.Format(" [Column(Storage = \"_{0}\", DbType = \"{1}\", CanBeNull = {2})]" + "\n", columns[i].ToString(), dbtypes[i].ToString(), canbenulls[i].ToString());
8 }
9
10 if (canbenulls[i] != null && canbenulls[i].ToString() == "true" && types[i].ToString() != "String")
11 {
12 strContentes += string.Format(" public Nullable<{0}> {1}" + "\n", types[i].ToString(), columns[i].ToString());
13 }
14 else
15 {
16 strContentes += string.Format(" public {0} {1}" + "\n", types[i].ToString(), columns[i].ToString());
17 }
18
19 strContentes = strContentes + " {" + "\n";
20 strContentes += string.Format(" get {{ return this._{0}; }}" + "\n", columns[i].ToString());
21 strContentes += string.Format(" set {{ this._{0} = value; }}" + "\n", columns[i].ToString());
22 strContentes = strContentes + " }" + "\n";
23
24 if (i != columns.Count - 1)
25 {
26 strContentes = strContentes + " " + "\n";
27 }
28 }
至于XML的解析,可以采用反序列化的方法,直接一下子就把整個XML轉化為類,這比起一步一步的解析XML來說,要容易得多了,具體請參考源代碼。
本文轉自 Eallies 51CTO部落格,原文連結:http://blog.51cto.com/eallies/79012,如需轉載請自行聯系原作者