上一篇中简单分享了下ORM的设计思路。现在开始讲如何用代码来实现上篇的设计模型。

我们建2个类库来分别抽象数据库表结构关系映射和SQL增删改查操作。

打开VS2010,新建2个类库。分别起名为Model,和DAL。

自己开发轻量级ORM(三)

Model层为数据库表结构关系映射

DAL层为 SQL增删改查操作的方法抽象封装

 

我们先从Model层开始。

数据库的表会包含表名,字段名称,字段类型,主键,外键等主要元素。我们在项目中为每张表建立一个Model类来抽象描述。

在Model类中我们定义常量TableName,用来描述数据库表名称。为表的字段逐一添加Model类属性,属性名和字段名相同。

由于SQL字段类型和.net数据类型不一致,我们在字段属性上添加自定义特性类DBType来描述对应的SQL字段类型。

字段会有主键,外键标识或者是虚拟字段标识。我们在字段属性上添加自定义特性类DBField来描述他们。

如:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using Model.Entities;
 6 using System.Data;
 7 namespace Model
 8 {
 9     [Serializable]
10     public class EmpInfoModel : BaseEntity
11     {
12         /// <summary>是否可以修改
13         /// </summary>
14         public const bool isCanMod = false;
15         /// <summary>数据库表名
16         /// </summary>
17         public const String TableName = "EmpInfo";
18         public EmpInfoModel()
19         { }
20 
21         private string _Id;
22         private string _Name;
23         private int? _isAllMoneyCheck;
24         private Guid? _MyGuid;
25         private Int16? _MySmallint;
26         private bool? _MyBool;
27         private string _Myntext;
28         [DBField(KeyType = DbKeyType.PK)]//主键标识
29         [DBType(SqlDBType = SqlDbType.NVarChar)]//字段对应SQLSERVER数据库字段类型
30         public virtual string Id
31         {
32             set { _Id = value; }
33             get { return _Id; }
34         }
35 
36         public string Name
37         {
38             set { _Name = value; }
39             get { return _Name; }
40         }
41 
42 
43         public int? isAllMoneyCheck
44         {
45             set { _isAllMoneyCheck = value; }
46             get { return _isAllMoneyCheck; }
47         }
48 
49         [DBType(SqlDBType = SqlDbType.UniqueIdentifier)]//字段对应SQLSERVER数据库字段类型
50         public Guid? MyGuid
51         {
52             set { _MyGuid = value; }
53             get { return _MyGuid; }
54         }
55 
56         [DBType(SqlDBType = SqlDbType.SmallInt)]//字段对应SQLSERVER数据库字段类型
57         public Int16? MySmallint
58         {
59             set { _MySmallint = value; }
60             get { return _MySmallint; }
61         }
62 
63         [DBType(SqlDBType = SqlDbType.Bit)]//字段对应SQLSERVER数据库字段类型
64         public bool? MyBool
65         {
66             set { _MyBool = value; }
67             get { return _MyBool; }
68         }
69         [DBType(SqlDBType = SqlDbType.NText)]//字段对应SQLSERVER数据库字段类型
70         public string Myntext
71         {
72             set { _Myntext = value; }
73             get { return _Myntext; }
74         }
75     }
76 }
View Code

相关文章: