Welcome

首页 / 软件开发 / .NET编程技术 / Dbml文件提取建表TSql-CodeSmith

Dbml文件提取建表TSql-CodeSmith2010-12-14 博客园 破狼在昨天一个大学师弟,他问我能不能将LinqToSql文件转化为创建表的TSql语 句,他是刚开始学习.NET,所以在网上下些示例看,但苦于没有数据库。所以就 有了这一篇博客,作为我的Code生成技术的CodeSimth的最后一篇示例。在下一 步Code 生成技术将转到Microsoft的T4模板,Code生成技术目前完成的有 CodeDom,CodeSmith模板,高手请不要拍砖,请直接跳过。

在Linq2Sql的Dbml文件其实就是一个Xml文件,记录着数据库与生成 Linq2SqlCode的数据信息,所以转化为TSql没有什么说的。我们需要提取其中的 数据库信息,在转化为我们的Tsql,在这里建立了DBTable、DBColumn、 DBAssociation三个实体类:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace DbmlToTable
7 {
8 public class DBTable
9 {
10
11 public DBTable()
12 {
13 Columns = new List<DBColumn>();
14 this.Associations = new List<DBAssociation>();
15 }
16
17 public string TableName
18 {
19 get;
20 set;
21 }
22
23 public List<DBColumn> Columns
24 {
25 get;
26 set;
27 }
28
29 public List<DBAssociation> Associations
30 {
31 get;
32 set;
33 }
34
35 }
36
37 public class DBColumn
38 {
39 public string Name
40 {
41 get;
42 set;
43 }
44
45 public string DBType
46 {
47 get;
48 set;
49 }
50
51 public bool IsPrimaryKey
52 {
53 get;
54 set;
55 }
56
57 public bool IsDbGenerated
58 {
59 get;
60 set;
61 }
62
63 public bool CanBeNull
64 {
65 get;
66 set;
67 }
68 }
69
70 public class DBAssociation
71 {
72 public string Name
73 {
74 get;
75 set;
76 }
77
78 public string ThisKey
79 {
80 get;
81 set;
82 }
83
84 public string OtherKey
85 {
86 get;
87 set;
88 }
89
90 public bool IsForeignKey
91 {
92 get;
93 set;
94 }
95 }
96
97 public class DBTableHlper
98 {
99 public static DBTable GetAssociationTable(List<DBTable> collection,string assName)
100 {
101
102 return collection.Find(t => t.Associations.Find(a => ! a.IsForeignKey && a.Name == assName) != null);
103 }
104 }
105 }
106
107