轻量级ORM

下载驱动封装库

打开https://github.com/yswenli/MongoDBOperator/releases下载二坏让封装库

澳门美高梅手机网站 1

 

DBHelper代码:

读取副节点

可节点默认是无法读取的,我们得以经过rs.setSlaveOk()方法来装Slave属性为true。上面是安装端口为27018之合乎节点可以开展读取

mongod –port 27018 –host localhost

> rs.setSlaveOk();

using System;
using System.Collections.Generic;
using System.Linq;

namespace Models
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public partial class BS_Template
    {
        /// <summary>
        /// 
        /// </summary>
        [IsId]
        [IsDBField]
        public string id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string typeCode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string type { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string path { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string folder { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [IsDBField]
        public string remarks { get; set; }
    }
}

下载驱动

开辟vs,使用nuget下充斥使

澳门美高梅手机网站 2

 

/// <summary>
/// 分页获取模板集合
/// </summary>
public List<BS_Template> GetList(ref PagerModel pager, string noticeType, string coreType, string name, Enums.TemplateType templateType)
{
    StringBuilder sql = new StringBuilder(string.Format(@"
        select *
        from BS_Template t
        where 1=1 "));

    if (!string.IsNullOrWhiteSpace(noticeType))
    {
        sql.AppendFormat(" and nt.name like '%{0}%'", noticeType);
    }

    if (!string.IsNullOrWhiteSpace(coreType))
    {
        sql.AppendFormat(" and ct.name like '%{0}%'", coreType);
    }

    if (!string.IsNullOrWhiteSpace(name))
    {
        sql.AppendFormat(" and t.name like '%{0}%'", name);
    }

    sql.AppendFormat(" and t.type = '{0}'", (int)templateType);

    string orderby = "order by cast(id as int)";
    pager = dbHelper.FindPageBySql<BS_Template>(sql.ToString(), orderby, pager.rows, pager.page);
    return pager.result as List<BS_Template>;
}

一、搭建Mongodb 副本集

副本集中发三独角色:

主节点:所有符合节点的数额均来源于于主节点,并且不得不对主节点举行读写操作。
顺应节点:数据出自于主节点,可以举办读取操作,但是非克开展摹写操作。
仲裁者:不带有数据为不与客户端互换,只于选出主节点之时段举行投票。

Mongodb最多协助50独可本集成员以及最好多7个选举成员,启动副本集后以启首先不善选举,在推举过程中,所有符合本集成员还不得不读取,直到选出出主节点后主节点才能够举办读写,可是在这一次副本成员好供查询服务。

假诺主节点要维持主节点的地方要各半秒发送一个ping请求,假设10秒内尚未拿走响应则标记为不可看,当半之上的入本集成员不可看,那么主节点将降也入节点。

内部设置成员的priority值可以先成员主节点,这一个值介于0-1000之间,默认为1,假诺此值为0,那么其的votes值也为0,只要votes为0的积极分子不可知投选举票,然而可以投否决票。可是咱们吧得以手动设置成员priority值为超出1底积极分子是否有投票权利。

在举办选的时,其他成员会作以下几点判断来进展投票参加选举的分子是否会看做主节点,选举步骤:

祥和是否能和主节点通讯。
涉足选举的成员是否比另外与选举的分子数时。
万一与选举的分子数量等则尝试用具有高priority的值的积极分子。

View Code

查询主节点

在使用rs.add方法上加成员的时节或会师影响选举来抉择主节点是哪位,查看主节点通过rs.isMaster()方法来查。

> rs.isMaster();
回到的情节被来几独可精通

{
“hosts” : [ //副本集成员
“localhost:27017”,
“localhost:27018”,
“localhost:27019”
],
“setName” : “rs0”, //副本集名称
“setVersion” : 3, //副本集配置版本
“ismaster” : true, //是否是主节点
“primary” : “localhost:27017”, //主节点成员的主机地址
“me” : “localhost:27017”, //当前所当主机
}

/// <summary>
/// 添加
/// </summary>
public void Insert(object obj)
{
    dbHelper.Insert(obj);
}

五、配置分片

澳门美高梅手机网站 3澳门美高梅手机网站 4

季、搭建筑里程由于服务器

mongodb提供了一个路由工具,它会合趁机大家下充斥包共下载,名字也mongosmongos.exe,通过她部署路由于功用。

起步路由于我们得添加参数--configdb,它的语法为:

--configdb 配置服务器副本集名称/配置服务器1地址端口,配置服务器1地址端口...

开行路由,并也路由指定一个端口,用于开放给客户端链接:

$ mongos --configdb conServer/localhost:27020,localhost:27021,localhost:27022 --port 27040

从这之后路由已经搭建得。

View Code

测试CS代码

 以下是测试代码: 

 1 /*****************************************************************************************************
 2 * 本代码版权归@wenli所有,All Rights Reserved (C) 2015-2017
 3 *****************************************************************************************************
 4 * CLR版本:4.0.30319.42000
 5 * 唯一标识:63fcdf18-8930-4a86-93ca-f99f5a020844
 6 * 机器名称:WENLI-PC
 7 * 联系人邮箱:wenguoli_520@qq.com
 8 *****************************************************************************************************
 9 * 项目名称:$projectname$
10 * 命名空间:MongoDBOperator.Test
11 * 类名称:Program
12 * 创建时间:2017/7/13 16:00:44
13 * 创建人:wenli
14 * 创建说明:
15 *****************************************************************************************************/
16 
17 using System;
18 using System.Linq;
19 using System.Threading.Tasks;
20 using MongoDBOperator.Interface;
21 using MongoDBOperator.Test.Model;
22 
23 namespace MongoDBOperator.Test
24 {
25     class Program
26     {
27         static void Main(string[] args)
28         {
29             Console.Title = "MongoDBOperator.Test";
30 
31             IOperator<Account> customerOperator = new MongoOperator<Account>();
32 
33 
34             var account = new Account();
35             account.FirstName = "li";
36             account.LastName = "wen";
37             account.Phone = "13800138000";
38             account.Email = "wenguoli_520@qq.com";
39             account.HomeAddress = new Address
40             {
41                 Address1 = "上海",
42                 Address2 = "徐汇",
43                 PostCode = "210001",
44                 City = "上海",
45                 Country = "中国"
46             };
47 
48             Console.WriteLine("Create");
49 
50             customerOperator.Add(account);            
53 
54             Console.WriteLine("Read");
55 
56             var c = customerOperator.Where(b => b.FirstName == "li").FirstOrDefault();
57 
58             Console.WriteLine("Update");
59 
60             c.FirstName = "guo li";
61 
62             customerOperator.Update(c);
63 
64             Console.WriteLine("Delete");
65 
66             customerOperator.Delete(c);
67 
68             customerOperator.DeleteAll();
69 
70             Console.ReadLine();
71 
72         }
73     }
74 }

 

vs调试效果如下:

澳门美高梅手机网站 5

 

 

 

转载请标明本文自:http://www.cnblogs.com/yswenli/p/7421909.html 
双重多内容欢迎star作者的github:https://github.com/yswenli/MongoDBOperator
就算发现本文有啊问题同其他指出,也随时欢迎交流~

 

澳门美高梅手机网站 6澳门美高梅手机网站 7

去除副本集

去副本集通过rs.remove方法来删除,它承受一个<localhost>:<port>这样的字符串。上面是去一个契合本集成员:

> rs.remove(‘localhost:27019’);

public BS_Template Get(string typeCode, Enums.TemplateType templateType)
{
    StringBuilder sql = new StringBuilder(string.Format(@"
        select *
        from BS_Template 
        where typeCode='{0}' 
        and type='{1}'", typeCode, (int)templateType));
    return dbHelper.FindBySql<BS_Template>(sql.ToString());
}
public BS_Template Get2(string templateId, Enums.TemplateType templateType)
{
    StringBuilder sql = new StringBuilder(string.Format(@"
        select *
        from BS_Template 
        where id='{0}' 
        and type='{1}'", templateId, (int)templateType));
    return dbHelper.FindBySql<BS_Template>(sql.ToString());
}

缓复制

经安装成员的slaveDelay的价并且优先值priority为0,来受眼前成员滞后多少秒后才开复制数据。

> rs.add({
> _id: 1,
> _host: ‘localhost:27017’,
> slaveDelay: 120,
> priority: 0
> })

View Code

目录管理

透过分子的buildIndexes的价并且优先值priority为0,来安装是否以备份机器上立平等之目,一般是选项才用于纯粹备份的服务器。

下的代码设置添加的合乎本集成员不创制索引。

> rs.add({
> _id: 1,
> _host: ‘localhost:27017’,
> buildIndexes: false
> priority: 0
> })

View Code

连配置

 打开app.config或web.config填写mongo连接配置

1 <?xml version="1.0" encoding="utf-8" ?>
2 <configuration>
3   <connectionStrings>
4     <add name="MongoServerSettings" connectionString="mongodb://admin:admin@localhost:27017/MongoTests?authSource=admin" />
5   </connectionStrings>
6 </configuration>

View Code

六使用MongoDB

View Code

部署分片服务器

经过mongodb提供的mongo进入到路由服务器被展开布置,把咱开首成立的老五只分片服务器通过sh.addShard()主意上加举行,这一个措施接受一个字符串里面的格式为host:port

$ mongo --port 27040 --host localhost

> sh.addShard('localhost:27030');
> sh.addShard('localhost:27031');
> sh.addShard('localhost:27032');

可透过rs.status()道吃回到的shards字段看是否充分成功。

 

仲裁者

仲裁者的面世是为着制止单纯发少单成员的适合本集,两只分子的契合本集投票可能无法满足一半上述之投票意况。

仲裁者不承担数据及客户端交换,唯有与选举的效率,需要专注的凡仲裁者一旦设置后尽管还为无从变成非仲裁者了。

先是部署一个可本集很粗略,下面的代码是布置了一个地点含有三独成员的符本集。

建两只分子的合本集,首先你得立三独数据库的存目录:

mkdir -p ./replDb/s0 ./replDb/s1 ./replDb/s2
然后我们启动三只符合本集成员,其中replSet参数后和的是入本集的名目,将需来涉嫌的积极分子的契合本集名称要一如既往。

mongod –dbpath ./replDb/s0 –port 27017 –replSet s0

mongod –dbpath ./replDb/s0 –port 27018 –replSet s0

mongod –dbpath ./replDb/s0 –port 27019 –replSet s0
始建仲裁者也同相当简单,建立一个空的数量目录,然后同其它符合本集成员一致装同样的抱本集名称启动,最后通过rs.add方法的第二单参数设置为true:

mongod –dbpath ./replDb/s5 –port 27020 –replSet s0

mongod –port 27017 –host localhost

> rs.add(‘localhost:27020’, true);

下一场通过Mongo Shell进入到端口为27017之分子中,并部署副本集。

mongod –port 27017 –host localhost
上及Mongo Shell后经rs.initiate方法来配置副本集。

> var conf = {
_id: ‘r0’,
version: 1,
members: [
{
_id: 0,
host: ‘localhost:27017’
},
{
_id: 1,
host: ‘localhost:27018’
},
{
_id: 2,
host: ‘localhost:27019’
},
{
_id: 3,
host: ‘localhost:27020’
}
]
};

> rs.initiate(conf);
initiate接受一个对象,对象_id为可本集名称,必须和启动副本集设置的一模一样才能够加加进去(本例为rs0)。version为本号,每当大家修改副本集配置的时刻这版本号都会合递加1,而members则也入本集成员,我们可当此处一遍性补充加完,也可只是上加一个尾再通过add方法添加,比如下边这样:

> rs.add(‘localhost:27018’);
> rs.add(‘localhost:27019’);

澳门美高梅手机网站 8澳门美高梅手机网站 9

查询符合本集配置

翻开副本集配置是经过rs.conf方法查询,重临包含有符合本集的配置内容.

> rs.conf();

View Code

其三、搭建分片服务器

法定提出我们的分片服务区至少在3个或上述才会表明出再好的性质,我们这边吧创建七只分片服务器。

盖分片服务器无强制要求假使契合本集,所以下就是创办了六只单机分片服务器,可是Mongodb接受分片服务器也可本集。

下成立三单空数据库目录,然后启动它们,在起步的时刻用添加--shardsvr坐象征即是一个分片服务器:

$ mkdir sh0 sh1 sh2

$ mongod --dbpath sh0 --shardsvr --port 27030

$ mongod --dbpath sh1 --shardsvr --port 27031

$ mongod --dbpath sh2 --shardsvr --port 27032

从这之后分片服务器也搭建完成。

View Code

躲成员

隐形成员通过安装成员的hidden属性为true并且优先值priority为0则可以隐藏此成员,隐藏成员不可能当主节点也非克当其他成员的复制源

> rs.add({
> _id: 1,
> _host: ‘localhost:27017’,
> hidden: true,
> priority: 0
> })

澳门美高梅手机网站 10

布局片键

到目前结束,分片服务器就搭建好,不过当前分片服务器无法正常干活,大家有着的操作都用于自由的一个主分片上操作,这是以分片服务器不晓怎么开展分片,所以我们还需要配置片键来告诉分片服务器依照什么来分片。

分片是因数据库集合中之文档的一个键拓展分片的,比如接纳username键,那么会依照是键的逐条就推行分片,而mongodb会自动平衡分片的数量。

Mongodb要求作片键的键必须是寻找引了的,所以咱们于确立片键在此之前要对键举办索引,建立后片键就是集结中之极端着重之目。

当生育环境遭受提议先想吓数据建构起目录和片键后初始操作数据,这样会见减轻分片服务器的负载。

先是我们以得展开分片的数据库及开分片功效,通过sh.enableSharding法被。

$ mongo --port 27040 --host localhost

> sh.enableSharding('test');

接下来于被分片的数据库被之test集合插入测试数据,注意这咱们还不曾开展部署片键,所以有的数据操作皆以分片服务器随机分配的一个主分片下边举办的。

> for(var i = 0; i < 100; i++){
    db.test.insert({
        username: 'user' + i,
        idNum: i
    })
}

这为username为片键,通过sh.shardCollection法举行确立,它的语法为:

sh.shardCollection(namespace, key, unique, options)

先是给大家设白手起家之片键建立目录:

> db.test.ensureIndex({'username': 1});

然后植片键:

> sh.shardCollection('test.test', {username:1});

等几分钟后,能够经sh.status主意查看数据分片的情形了,可以从中很亮的见什么数据在什么人分片服务器下面,并且经过explain计来查我们询问的过程被怎么着分片服务器参预了查询。

/// <summary>
/// 修改
/// </summary>
public void Update(object obj)
{
    dbHelper.Update(obj);
}

老二、搭建配置服务器

先是搭建配置服务器,配置服务器如同分片的大脑,保存在集群和数目标叙说音讯。

盖Mongodb3.4版本后待配置服务器必须配备为契合本集,所以要被配备服务器配置副本集

首先创设六只缺损的数据库目录,用于搭建配置服务器的适合本集,并各自启动它们,在起步之时节用添加大家符合本集的名号与--configsvr来代表这是一个安排服务器,并分别指定不同的端口。

$ mkdir config0 config1 config2

$ mongod --dbpath config0 --replSet conServer --configsvr --port 27020

$ mongod --dbpath config1 --replSet conServer --configsvr --port 27021

$ mongod --dbpath config2 --replSet conServer --configsvr --port 27020

然后经mongo随意进入一个合乎本集成员,并也布局服务器的符合本集举行配备:

$ mongo --port 27020 --host localhost

> var conf = {
    _id: 'conServer',
    version: 1,
    members: [
        {
            _id: 0,
            host: 'localhost:27020'
        },
        {
            _id: 1,
            host: 'localhost:27021'
        },
        {
            _id: 2,
            host: 'localhost:27022'
        }
    ]
};

> rs.initiate(conf);

由来配置服务器配置好。

澳门美高梅手机网站,View Code

何以用:

Model层的计划性:

/// <summary>
/// 删除
/// </summary>
public void BatchDelete(string ids)
{
    dbHelper.BatchDelete<BS_Template>(ids);
}

   
Models目录中的切近及其特性与数据库中之声明及字段是一点一滴对应的,Models全体出于生成器生成,并且不允手动修改。ExtModels目录中的类是扩张类,紧要用以查询与显,比如表中存的凡code,但你待关联查询任何一样布置表中的name,就足以在这扩充类吃扩充一个用于呈现的name字段。Models和ExtModels目录的中类都是partial修饰。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBUtil;
using Models;

namespace DAL
{
    /// <summary>
    /// 模板
    /// </summary>
    public class TemplateDal
    {
        #region 变量
        private DBHelper dbHelper = new DBHelper();
        #endregion

        #region 分页获取模板集合
        /// <summary>
        /// 分页获取模板集合
        /// </summary>
        public List<BS_Template> GetList(ref PagerModel pager, string noticeType, string coreType, string name, Enums.TemplateType templateType)
        {
            StringBuilder sql = new StringBuilder(string.Format(@"
                select *
                from BS_Template t
                where 1=1 "));

            if (!string.IsNullOrWhiteSpace(noticeType))
            {
                sql.AppendFormat(" and nt.name like '%{0}%'", noticeType);
            }

            if (!string.IsNullOrWhiteSpace(coreType))
            {
                sql.AppendFormat(" and ct.name like '%{0}%'", coreType);
            }

            if (!string.IsNullOrWhiteSpace(name))
            {
                sql.AppendFormat(" and t.name like '%{0}%'", name);
            }

            sql.AppendFormat(" and t.type = '{0}'", (int)templateType);

            string orderby = "order by cast(id as int)";
            pager = dbHelper.FindPageBySql<BS_Template>(sql.ToString(), orderby, pager.rows, pager.page);
            return pager.result as List<BS_Template>;
        }
        #endregion

        #region 获取字段关联模板集合
        /// <summary>
        /// 获取字段关联模板集合
        /// </summary>
        public List<BS_Template> GetList(string fieldId)
        {
            StringBuilder sql = new StringBuilder(string.Format(@"
                select *
                from BS_Template t
                left join BS_TplFieldRelation r on r.templateId=t.id
                left join BS_TplField f on f.id=r.fieldId  
                where f.id='{0}'", fieldId));
            return dbHelper.FindListBySql<BS_Template>(sql.ToString());
        }
        #endregion

        #region 获取
        public BS_Template Get(string typeCode, Enums.TemplateType templateType)
        {
            StringBuilder sql = new StringBuilder(string.Format(@"
                select *
                from BS_Template 
                where typeCode='{0}' 
                and type='{1}'", typeCode, (int)templateType));
            return dbHelper.FindBySql<BS_Template>(sql.ToString());
        }
        public BS_Template Get2(string templateId, Enums.TemplateType templateType)
        {
            StringBuilder sql = new StringBuilder(string.Format(@"
                select *
                from BS_Template 
                where id='{0}' 
                and type='{1}'", templateId, (int)templateType));
            return dbHelper.FindBySql<BS_Template>(sql.ToString());
        }
        #endregion

        #region GetMaxId
        /// <summary>
        /// GetMaxId
        /// </summary>
        public int GetMaxId()
        {
            return dbHelper.GetMaxID<BS_Template>("id");
        }
        #endregion

        #region 添加
        /// <summary>
        /// 添加
        /// </summary>
        public void Insert(object obj)
        {
            dbHelper.Insert(obj);
        }
        #endregion

        #region 修改
        /// <summary>
        /// 修改
        /// </summary>
        public void Update(object obj)
        {
            dbHelper.Update(obj);
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        public void Del(int id)
        {
            dbHelper.Delete<BS_Template>(id);
        }
        /// <summary>
        /// 删除
        /// </summary>
        public void BatchDelete(string ids)
        {
            dbHelper.BatchDelete<BS_Template>(ids);
        }
        /// <summary>
        /// 删除
        /// </summary>
        public void Delete(string conditions)
        {
            dbHelper.Delete<BS_Template>(conditions);
        }
        #endregion

    }
}

澳门美高梅手机网站 11澳门美高梅手机网站 12

View Code

    添加:

    分页查询列表:

    完整DAL:

    查询sql书写规范:

澳门美高梅手机网站 13澳门美高梅手机网站 14

澳门美高梅手机网站 15澳门美高梅手机网站 16

    按照规则查询实体:

澳门美高梅手机网站 17澳门美高梅手机网站 18

View Code

    按照条件去:

    数据库事务:

/// <summary>
/// 删除
/// </summary>
public void Del(int id)
{
    dbHelper.Delete<BS_Template>(id);
}

澳门美高梅手机网站 19澳门美高梅手机网站 20

/// <summary>
/// 查询列表
/// </summary>
public List<BS_Test> GetList(string name)
{
    StringBuilder sql = new StringBuilder(string.Format(@"
        select *
        from BS_Test t
        where 1=1 "));

    if (!string.IsNullOrWhiteSpace(name))
    {
        sql.AppendFormat(" and t.name like '%{0}%'", name);
    }

    return dbHelper.FindListBySql<BS_Test>(sql.ToString());
}

 

    依据ID查询实体:

    select换行,from换行,join换行,where换行,and换行。

/// <summary>
/// 分页获取模板集合
/// </summary>
public List<BS_Template> GetList(ref PagerModel pager, string noticeType, string coreType, string name, Enums.TemplateType templateType)
{
    StringBuilder sql = new StringBuilder(string.Format(@"
        select *
        from BS_Template t
        where 1=1 "));

    if (!string.IsNullOrWhiteSpace(noticeType))
    {
        sql.AppendFormat(" and nt.name like '%{0}%'", noticeType);
    }

    if (!string.IsNullOrWhiteSpace(coreType))
    {
        sql.AppendFormat(" and ct.name like '%{0}%'", coreType);
    }

    if (!string.IsNullOrWhiteSpace(name))
    {
        sql.AppendFormat(" and t.name like '%{0}%'", name);
    }

    sql.AppendFormat(" and t.type = '{0}'", (int)templateType);

    string orderby = "order by cast(id as int)";
    pager = dbHelper.FindPageBySql<BS_Template>(sql.ToString(), orderby, pager.rows, pager.page);
    return pager.result as List<BS_Template>;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Objects.DataClasses;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Reflection;
using System.Text;
using Models;
using MySql.Data.MySqlClient;

namespace DBUtil
{
    /// <summary>
    /// 数据库操作类
    /// 2016年09月09日
    /// </summary>
    public class DBHelper
    {
        #region 变量
        /// <summary>
        /// 数据库类型
        /// </summary>
        private static string m_DBType = ConfigurationManager.AppSettings["DBType"];
        /// <summary>
        /// 数据库类型
        /// </summary>
        private static bool m_AutoIncrement = ConfigurationManager.AppSettings["AutoIncrement"].ToLower() == "true" ? true : false;
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        private static string m_ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        /// <summary>
        /// 事务
        /// </summary>
        [ThreadStatic]
        private static DbTransaction m_Tran;
        /// <summary>
        /// 带参数的SQL插入和修改语句中,参数前面的符号
        /// </summary>
        private static string m_ParameterMark = GetParameterMark();
        #endregion

        #region 构造函数
        /// <summary>
        /// 数据库操作类
        /// </summary>
        public DBHelper()
        {
        }
        #endregion

        #region 生成变量
        #region 生成 IDbCommand
        /// <summary>
        /// 生成 IDbCommand
        /// </summary>
        private DbCommand GetCommand()
        {
            DbCommand command = null;

            switch (m_DBType)
            {
                case "oracle":
                    command = new OracleCommand();
                    break;
                case "mssql":
                    command = new SqlCommand();
                    break;
                case "mysql":
                    command = new MySqlCommand();
                    break;
                case "sqlite":
                    command = new SQLiteCommand();
                    break;
            }

            return command;
        }
        /// <summary>
        /// 生成 IDbCommand
        /// </summary>
        private DbCommand GetCommand(string sql, DbConnection conn)
        {
            DbCommand command = null;

            switch (m_DBType)
            {
                case "oracle":
                    command = new OracleCommand(sql);
                    command.Connection = conn;
                    break;
                case "mssql":
                    command = new SqlCommand(sql);
                    command.Connection = conn;
                    break;
                case "mysql":
                    command = new MySqlCommand(sql);
                    command.Connection = conn;
                    break;
                case "sqlite":
                    command = new SQLiteCommand(sql);
                    command.Connection = conn;
                    break;
            }

            return command;
        }
        #endregion

        #region 生成 IDbConnection
        /// <summary>
        /// 生成 IDbConnection
        /// </summary>
        private static DbConnection GetConnection()
        {
            DbConnection conn = null;

            switch (m_DBType)
            {
                case "oracle":
                    conn = new OracleConnection(m_ConnectionString);
                    break;
                case "mssql":
                    conn = new SqlConnection(m_ConnectionString);
                    break;
                case "mysql":
                    conn = new MySqlConnection(m_ConnectionString);
                    break;
                case "sqlite":
                    conn = new SQLiteConnection(m_ConnectionString);
                    break;
            }

            return conn;
        }
        #endregion

        #region 生成 IDbDataAdapter
        /// <summary>
        /// 生成 IDbDataAdapter
        /// </summary>
        private DbDataAdapter GetDataAdapter(DbCommand cmd)
        {
            DbDataAdapter dataAdapter = null;

            switch (m_DBType)
            {
                case "oracle":
                    dataAdapter = new OracleDataAdapter();
                    dataAdapter.SelectCommand = cmd;
                    break;
                case "mssql":
                    dataAdapter = new SqlDataAdapter();
                    dataAdapter.SelectCommand = cmd;
                    break;
                case "mysql":
                    dataAdapter = new MySqlDataAdapter();
                    dataAdapter.SelectCommand = cmd;
                    break;
                case "sqlite":
                    dataAdapter = new SQLiteDataAdapter();
                    dataAdapter.SelectCommand = cmd;
                    break;
            }

            return dataAdapter;
        }
        #endregion

        #region 生成 m_ParameterMark
        /// <summary>
        /// 生成 m_ParameterMark
        /// </summary>
        private static string GetParameterMark()
        {
            switch (m_DBType)
            {
                case "oracle":
                    return ":";
                case "mssql":
                    return "@";
                case "mysql":
                    return "@";
                case "sqlite":
                    return ":";
            }
            return ":";
        }
        #endregion

        #region 生成 DbParameter
        /// <summary>
        /// 生成 DbParameter
        /// </summary>
        private DbParameter GetDbParameter(string name, object value)
        {
            DbParameter dbParameter = null;

            switch (m_DBType)
            {
                case "oracle":
                    dbParameter = new OracleParameter(name, value);
                    break;
                case "mssql":
                    dbParameter = new SqlParameter(name, value);
                    break;
                case "mysql":
                    dbParameter = new MySqlParameter(name, value);
                    break;
                case "sqlite":
                    dbParameter = new SQLiteParameter(name, value);
                    break;
            }

            return dbParameter;
        }
        #endregion
        #endregion

        #region 基础方法
        #region  执行简单SQL语句
        #region Exists
        public bool Exists(string sqlString)
        {
            using (DbConnection conn = GetConnection())
            {
                using (DbCommand cmd = GetCommand(sqlString, conn))
                {
                    try
                    {
                        conn.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        cmd.Dispose();
                        conn.Close();
                    }
                }
            }
        }
        #endregion

        #region 执行SQL语句,返回影响的记录数
        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="sqlString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string sqlString)
        {
            DbConnection conn = m_Tran == null ? GetConnection() : m_Tran.Connection;
            using (DbCommand cmd = GetCommand(sqlString, conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open) conn.Open();
                    if (m_Tran != null) cmd.Transaction = m_Tran;
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                    if (m_Tran == null) conn.Close();
                }
            }
        }
        #endregion

        #region 执行一条计算查询结果语句,返回查询结果
        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)
        /// </summary>
        /// <param name="sqlString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public object GetSingle(string sqlString)
        {
            using (DbConnection conn = GetConnection())
            {
                using (DbCommand cmd = GetCommand(sqlString, conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open) conn.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        cmd.Dispose();
                    }
                }
            }
        }
        #endregion

        #region 执行查询语句,返回IDataReader
        /// <summary>
        /// 执行查询语句,返回IDataReader ( 注意:调用该方法后,一定要对IDataReader进行Close )
        /// </summary>
        /// <param name="sqlString">查询语句</param>
        /// <returns>IDataReader</returns>
        public DbDataReader ExecuteReader(string sqlString)
        {
            DbConnection conn = GetConnection();
            DbCommand cmd = GetCommand(sqlString, conn);
            try
            {
                if (conn.State != ConnectionState.Open) conn.Open();
                DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 执行查询语句,返回DataSet
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="sqlString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sqlString)
        {
            using (DbConnection conn = GetConnection())
            {
                DataSet ds = new DataSet();
                try
                {
                    conn.Open();
                    using (DbCommand cmd = GetCommand(sqlString, conn))
                    {
                        DbDataAdapter adapter = GetDataAdapter(cmd);
                        adapter.Fill(ds, "ds");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
                return ds;
            }
        }
        #endregion
        #endregion

        #region 执行带参数的SQL语句
        #region 执行SQL语句,返回影响的记录数
        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString, params DbParameter[] cmdParms)
        {
            DbConnection conn = m_Tran == null ? GetConnection() : m_Tran.Connection;
            using (DbCommand cmd = GetCommand())
            {
                try
                {
                    PrepareCommand(cmd, conn, m_Tran, SQLString, cmdParms);
                    int rows = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return rows;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    if (m_Tran == null) conn.Close();
                }
            }
        }
        #endregion

        #region 执行查询语句,返回IDataReader
        /// <summary>
        /// 执行查询语句,返回IDataReader ( 注意:调用该方法后,一定要对IDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>IDataReader</returns>
        public DbDataReader ExecuteReader(string sqlString, params DbParameter[] cmdParms)
        {
            DbConnection conn = GetConnection();
            DbCommand cmd = GetCommand();
            try
            {
                PrepareCommand(cmd, conn, null, sqlString, cmdParms);
                DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region 执行查询语句,返回DataSet
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="sqlString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sqlString, params DbParameter[] cmdParms)
        {
            DbConnection conn = GetConnection();
            DbCommand cmd = GetCommand();
            PrepareCommand(cmd, conn, null, sqlString, cmdParms);
            using (DbDataAdapter da = GetDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds, "ds");
                    cmd.Parameters.Clear();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.Dispose();
                    conn.Close();
                }
                return ds;
            }
        }
        #endregion

        #region PrepareCommand
        private void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open) conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null) cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (DbParameter parm in cmdParms)
                {
                    cmd.Parameters.Add(parm);
                }
            }
        }
        #endregion
        #endregion
        #endregion

        #region 增删改查
        #region 获取最大编号
        /// <summary>
        /// 获取最大编号
        /// </summary>
        /// <typeparam name="T">实体Model</typeparam>
        /// <param name="key">主键</param>
        public int GetMaxID<T>(string key)
        {
            Type type = typeof(T);

            string sql = null;
            switch (m_DBType)
            {
                case "oracle":
                    sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
                    break;
                case "mssql":
                    sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
                    break;
                case "mysql":
                    sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
                    break;
                case "sqlite":
                    sql = string.Format("SELECT Max(cast({0} as int)) FROM {1}", key, type.Name);
                    break;
            }

            using (DbConnection conn = GetConnection())
            {
                using (IDbCommand cmd = GetCommand(sql, conn))
                {
                    try
                    {
                        conn.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return 1;
                        }
                        else
                        {
                            return int.Parse(obj.ToString()) + 1;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        cmd.Dispose();
                        conn.Close();
                    }
                }
            }
        }
        #endregion

        #region 添加
        /// <summary>
        /// 添加
        /// </summary>
        public void Insert(object obj)
        {
            Insert(obj, m_AutoIncrement);
        }
        /// <summary>
        /// 添加
        /// </summary>
        public void Insert(object obj, bool autoIncrement)
        {
            StringBuilder strSql = new StringBuilder();
            Type type = obj.GetType();
            strSql.Append(string.Format("insert into {0}(", type.Name));

            PropertyInfo[] propertyInfoList = GetEntityProperties(type);
            List<string> propertyNameList = new List<string>();
            int savedCount = 0;
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > 0 && autoIncrement) return;
                if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > 0)
                {
                    propertyNameList.Add(propertyInfo.Name);
                    savedCount++;
                }
            }

            strSql.Append(string.Format("{0})", string.Join(",", propertyNameList.ToArray())));
            strSql.Append(string.Format(" values ({0})", string.Join(",", propertyNameList.ConvertAll<string>(a => m_ParameterMark + a).ToArray())));
            DbParameter[] parameters = new DbParameter[savedCount];
            int k = 0;
            for (int i = 0; i < propertyInfoList.Length && savedCount > 0; i++)
            {
                PropertyInfo propertyInfo = propertyInfoList[i];
                if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > 0 && autoIncrement) return;
                if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > 0)
                {
                    object val = propertyInfo.GetValue(obj, null);
                    DbParameter param = GetDbParameter(m_ParameterMark + propertyInfo.Name, val == null ? DBNull.Value : val);
                    parameters[k++] = param;
                }
            }

            ExecuteSql(strSql.ToString(), parameters);
        }
        #endregion

        #region 修改
        /// <summary>
        /// 修改
        /// </summary>
        public void Update(object obj)
        {
            object oldObj = Find(obj, false);
            if (oldObj == null) throw new Exception("无法获取到旧数据");

            StringBuilder strSql = new StringBuilder();
            Type type = obj.GetType();
            strSql.Append(string.Format("update {0} ", type.Name));

            PropertyInfo[] propertyInfoList = GetEntityProperties(type);
            List<string> propertyNameList = new List<string>();
            int savedCount = 0;
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > 0)
                {
                    object oldVal = propertyInfo.GetValue(oldObj, null);
                    object val = propertyInfo.GetValue(obj, null);
                    if (!object.Equals(oldVal, val))
                    {
                        propertyNameList.Add(propertyInfo.Name);
                        savedCount++;
                    }
                }
            }

            strSql.Append(string.Format(" set "));
            DbParameter[] parameters = new DbParameter[savedCount];
            StringBuilder sbPros = new StringBuilder();
            int k = 0;
            for (int i = 0; i < propertyInfoList.Length && savedCount > 0; i++)
            {
                PropertyInfo propertyInfo = propertyInfoList[i];
                if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > 0)
                {
                    object oldVal = propertyInfo.GetValue(oldObj, null);
                    object val = propertyInfo.GetValue(obj, null);
                    if (!object.Equals(oldVal, val))
                    {
                        sbPros.Append(string.Format(" {0}={1}{0},", propertyInfo.Name, m_ParameterMark));
                        DbParameter param = GetDbParameter(m_ParameterMark + propertyInfo.Name, val == null ? DBNull.Value : val);
                        parameters[k++] = param;
                    }
                }
            }
            if (sbPros.Length > 0)
            {
                strSql.Append(sbPros.ToString(0, sbPros.Length - 1));
            }
            strSql.Append(string.Format(" where {0}='{1}'", GetIdName(obj.GetType()), GetIdVal(obj).ToString()));

            if (savedCount > 0)
            {
                ExecuteSql(strSql.ToString(), parameters);
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 根据Id删除
        /// </summary>
        public void Delete<T>(int id)
        {
            Type type = typeof(T);
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(string.Format("delete from {0} where {2}='{1}'", type.Name, id, GetIdName(type)));

            ExecuteSql(sbSql.ToString());
        }
        /// <summary>
        /// 根据Id集合删除
        /// </summary>
        public void BatchDelete<T>(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids)) return;

            Type type = typeof(T);
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(string.Format("delete from {0} where {2} in ({1})", type.Name, ids, GetIdName(type)));

            ExecuteSql(sbSql.ToString());
        }
        /// <summary>
        /// 根据条件删除
        /// </summary>
        public void Delete<T>(string conditions)
        {
            if (string.IsNullOrWhiteSpace(conditions)) return;

            Type type = typeof(T);
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(string.Format("delete from {0} where {1}", type.Name, conditions));

            ExecuteSql(sbSql.ToString());
        }
        #endregion

        #region 获取实体
        #region 根据实体获取实体
        /// <summary>
        /// 根据实体获取实体
        /// </summary>
        private object Find(object obj, bool readCache = true)
        {
            Type type = obj.GetType();

            object result = Activator.CreateInstance(type);
            bool hasValue = false;
            IDataReader rd = null;

            string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, GetIdVal(obj), GetIdName(obj.GetType()));

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            if (hasValue)
            {
                return result;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 根据Id获取实体
        /// <summary>
        /// 根据Id获取实体
        /// </summary>
        private object FindById(Type type, int id)
        {
            object result = Activator.CreateInstance(type);
            IDataReader rd = null;
            bool hasValue = false;

            string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            if (hasValue)
            {
                return result;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 根据Id获取实体
        /// <summary>
        /// 根据Id获取实体
        /// </summary>
        public T FindById<T>(string id) where T : new()
        {
            Type type = typeof(T);
            T result = (T)Activator.CreateInstance(type);
            IDataReader rd = null;
            bool hasValue = false;

            string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            if (hasValue)
            {
                return result;
            }
            else
            {
                return default(T);
            }
        }
        #endregion

        #region 根据sql获取实体
        /// <summary>
        /// 根据sql获取实体
        /// </summary>
        public T FindBySql<T>(string sql) where T : new()
        {
            Type type = typeof(T);
            T result = (T)Activator.CreateInstance(type);
            IDataReader rd = null;
            bool hasValue = false;

            try
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = new List<string>();
                for (int i = 0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).ToUpper());
                }

                while (rd.Read())
                {
                    hasValue = true;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro in propertyInfoList)
                    {
                        if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                        {
                            continue;
                        }

                        pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            if (hasValue)
            {
                return result;
            }
            else
            {
                return default(T);
            }
        }
        #endregion
        #endregion

        #region 获取列表
        /// <summary>
        /// 获取列表
        /// </summary>
        public List<T> FindListBySql<T>(string sql) where T : new()
        {
            List<T> list = new List<T>();
            object obj;
            IDataReader rd = null;

            try
            {
                rd = ExecuteReader(sql);

                if (typeof(T) == typeof(int))
                {
                    while (rd.Read())
                    {
                        list.Add((T)rd[0]);
                    }
                }
                else if (typeof(T) == typeof(string))
                {
                    while (rd.Read())
                    {
                        list.Add((T)rd[0]);
                    }
                }
                else
                {
                    PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();

                    int fcnt = rd.FieldCount;
                    List<string> fileds = new List<string>();
                    for (int i = 0; i < fcnt; i++)
                    {
                        fileds.Add(rd.GetName(i).ToUpper());
                    }

                    while (rd.Read())
                    {
                        IDataRecord record = rd;
                        obj = new T();


                        foreach (PropertyInfo pro in propertyInfoList)
                        {
                            if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                            {
                                continue;
                            }

                            pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                        }
                        list.Add((T)obj);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            return list;
        }
        #endregion

        #region 获取列表
        /// <summary>
        /// 获取列表
        /// </summary>
        public List<T> FindListBySql<T>(string sql, params DbParameter[] cmdParms) where T : new()
        {
            List<T> list = new List<T>();
            object obj;
            IDataReader rd = null;

            try
            {
                rd = ExecuteReader(sql, cmdParms);

                if (typeof(T) == typeof(int))
                {
                    while (rd.Read())
                    {
                        list.Add((T)rd[0]);
                    }
                }
                else if (typeof(T) == typeof(string))
                {
                    while (rd.Read())
                    {
                        list.Add((T)rd[0]);
                    }
                }
                else
                {
                    PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();

                    int fcnt = rd.FieldCount;
                    List<string> fileds = new List<string>();
                    for (int i = 0; i < fcnt; i++)
                    {
                        fileds.Add(rd.GetName(i).ToUpper());
                    }

                    while (rd.Read())
                    {
                        IDataRecord record = rd;
                        obj = new T();


                        foreach (PropertyInfo pro in propertyInfoList)
                        {
                            if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
                            {
                                continue;
                            }

                            pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
                        }
                        list.Add((T)obj);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.Dispose();
                }
            }

            return list;
        }
        #endregion

        #region 分页获取列表
        /// <summary>
        /// 分页(任意entity,尽量少的字段)
        /// </summary>
        public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage) where T : new()
        {
            PagerModel pagerModel = new PagerModel(currentPage, pageSize);

            using (DbConnection connection = GetConnection())
            {
                connection.Open();
                IDbCommand cmd = null;
                StringBuilder sb = new StringBuilder();
                string commandText = null;
                int startRow = 0;
                int endRow = 0;
                switch (m_DBType)
                {
                    case "oracle":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);
                        endRow = startRow + pageSize;

                        sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.Append(" ) row_limit where rownum <= ");
                        sb.Append(endRow);
                        sb.Append(" ) where rownum_ >");
                        sb.Append(startRow);
                        #endregion
                        break;
                    case "mssql":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1) + 1;
                        endRow = startRow + pageSize - 1;

                        sb.Append(string.Format(@"
                            select * from 
                            (select ROW_NUMBER() over({1}) as rowNumber, t.* from ({0}) t) tempTable
                            where rowNumber between {2} and {3} ", sql, orderby, startRow, endRow));
                        #endregion
                        break;
                    case "mysql":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);

                        sb.Append("select * from (");
                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
                        #endregion
                        break;
                    case "sqlite":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);

                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.AppendFormat(" limit {0} offset {1}", pageSize, startRow);
                        #endregion
                        break;
                }

                List<T> list = FindListBySql<T>(sb.ToString());
                pagerModel.result = list;
            }

            return pagerModel;
        }
        #endregion

        #region 分页获取列表
        /// <summary>
        /// 分页(任意entity,尽量少的字段)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <returns></returns>
        public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage, params DbParameter[] cmdParms) where T : new()
        {
            PagerModel pagerModel = new PagerModel(currentPage, pageSize);

            using (DbConnection connection = GetConnection())
            {
                connection.Open();
                IDbCommand cmd = null;
                StringBuilder sb = new StringBuilder();
                string commandText = null;
                int startRow = 0;
                int endRow = 0;
                switch (m_DBType)
                {
                    case "oracle":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);
                        endRow = startRow + pageSize;

                        sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.Append(" ) row_limit where rownum <= ");
                        sb.Append(endRow);
                        sb.Append(" ) where rownum_ >");
                        sb.Append(startRow);
                        #endregion
                        break;
                    case "mssql":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1) + 1;
                        endRow = startRow + pageSize - 1;

                        sb.Append(string.Format(@"
                            select * from 
                            (select ROW_NUMBER() over({1}) as rowNumber, t.* from ({0}) t) tempTable
                            where rowNumber between {2} and {3} ", sql, orderby, startRow, endRow));
                        #endregion
                        break;
                    case "mysql":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);

                        sb.Append("select * from (");
                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
                        #endregion
                        break;
                    case "sqlite":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);

                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.AppendFormat(" limit {0} offset {1}", pageSize, startRow);
                        #endregion
                        break;
                }

                List<T> list = FindListBySql<T>(sb.ToString(), cmdParms);
                pagerModel.result = list;
            }

            return pagerModel;
        }


        #endregion

        #region 分页获取列表
        /// <summary>
        /// 分页(任意entity,尽量少的字段)
        /// </summary>
        public DataSet FindPageBySql(string sql, string orderby, int pageSize, int currentPage, out int totalCount, params DbParameter[] cmdParms)
        {
            DataSet ds = null;

            using (DbConnection connection = GetConnection())
            {
                connection.Open();
                IDbCommand cmd = null;
                StringBuilder sb = new StringBuilder();
                string commandText = null;
                int startRow = 0;
                int endRow = 0;
                totalCount = 0;
                switch (m_DBType)
                {
                    case "oracle":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        totalCount = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);
                        endRow = startRow + pageSize;

                        sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.Append(" ) row_limit where rownum <= ");
                        sb.Append(endRow);
                        sb.Append(" ) where rownum_ >");
                        sb.Append(startRow);
                        #endregion
                        break;
                    case "mssql":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        totalCount = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1) + 1;
                        endRow = startRow + pageSize - 1;

                        sb.Append(string.Format(@"
                            select * from 
                            (select ROW_NUMBER() over({1}) as rowNumber, t.* from ({0}) t) tempTable
                            where rowNumber between {2} and {3} ", sql, orderby, startRow, endRow));
                        #endregion
                        break;
                    case "mysql":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        totalCount = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);

                        sb.Append("select * from (");
                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
                        #endregion
                        break;
                    case "sqlite":
                        #region 分页查询语句
                        commandText = string.Format("select count(*) from ({0}) T", sql);
                        cmd = GetCommand(commandText, connection);
                        totalCount = int.Parse(cmd.ExecuteScalar().ToString());

                        startRow = pageSize * (currentPage - 1);

                        sb.Append(sql);
                        if (!string.IsNullOrWhiteSpace(orderby))
                        {
                            sb.Append(" ");
                            sb.Append(orderby);
                        }
                        sb.AppendFormat(" limit {0} offset {1}", pageSize, startRow);
                        #endregion
                        break;
                }

                ds = Query(sql, cmdParms);
            }
            return ds;
        }
        #endregion

        #region getReaderValue 转换数据
        /// <summary>
        /// 转换数据
        /// </summary>
        private Object getReaderValue(Object rdValue, Type ptype)
        {
            if (ptype == typeof(double))
                return Convert.ToDouble(rdValue);

            if (ptype == typeof(decimal))
                return Convert.ToDecimal(rdValue);

            if (ptype == typeof(int))
                return Convert.ToInt32(rdValue);

            if (ptype == typeof(long))
                return Convert.ToInt64(rdValue);

            if (ptype == typeof(DateTime))
                return Convert.ToDateTime(rdValue);

            if (ptype == typeof(Nullable<double>))
                return Convert.ToDouble(rdValue);

            if (ptype == typeof(Nullable<decimal>))
                return Convert.ToDecimal(rdValue);

            if (ptype == typeof(Nullable<int>))
                return Convert.ToInt32(rdValue);

            if (ptype == typeof(Nullable<long>))
                return Convert.ToInt64(rdValue);

            if (ptype == typeof(Nullable<DateTime>))
                return Convert.ToDateTime(rdValue);

            return rdValue;
        }
        #endregion

        #region 获取主键名称
        /// <summary>
        /// 获取主键名称
        /// </summary>
        public string GetIdName(Type type)
        {
            PropertyInfo[] propertyInfoList = GetEntityProperties(type);
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > 0)
                {
                    return propertyInfo.Name;
                }
            }
            return "Id";
        }
        #endregion

        #region 获取主键值
        /// <summary>
        /// 获取主键名称
        /// </summary>
        public object GetIdVal(object val)
        {
            string idName = GetIdName(val.GetType());
            if (!string.IsNullOrWhiteSpace(idName))
            {
                return val.GetType().GetProperty(idName).GetValue(val, null);
            }
            return 0;
        }
        #endregion

        #region 获取实体类属性
        /// <summary>
        /// 获取实体类属性
        /// </summary>
        private PropertyInfo[] GetEntityProperties(Type type)
        {
            List<PropertyInfo> result = new List<PropertyInfo>();
            PropertyInfo[] propertyInfoList = type.GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                if (propertyInfo.GetCustomAttributes(typeof(EdmRelationshipNavigationPropertyAttribute), false).Length == 0
                    && propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false).Length == 0)
                {
                    result.Add(propertyInfo);
                }
            }
            return result.ToArray();
        }
        #endregion

        #region 获取基类
        /// <summary>
        /// 获取基类
        /// </summary>
        public Type GetBaseType(Type type)
        {
            while (type.BaseType != null && type.BaseType.Name != typeof(Object).Name)
            {
                type = type.BaseType;
            }
            return type;
        }
        #endregion
        #endregion

        #region 事务
        #region 开始事务
        /// <summary>
        /// 开始事务
        /// </summary>
        public static void BeginTransaction()
        {
            DbConnection conn = GetConnection();
            if (conn.State != ConnectionState.Open) conn.Open();
            m_Tran = conn.BeginTransaction();
        }
        #endregion

        #region 提交事务
        /// <summary>
        /// 提交事务
        /// </summary>
        public static void CommitTransaction()
        {
            DbConnection conn = m_Tran.Connection;
            try
            {
                m_Tran.Commit();
            }
            catch (Exception ex)
            {
                m_Tran.Rollback();
            }
            finally
            {
                if (conn.State == ConnectionState.Open) conn.Close();
                m_Tran.Dispose();
                m_Tran = null;
            }
        }
        #endregion

        #region 回滚事务(出错时调用该方法回滚)
        /// <summary>
        /// 回滚事务(出错时调用该方法回滚)
        /// </summary>
        public static void RollbackTransaction()
        {
            DbConnection conn = m_Tran.Connection;
            m_Tran.Rollback();
            if (conn.State == ConnectionState.Open) conn.Close();
        }
        #endregion
        #endregion
    }
}

    按照ID批量删除:

/// <summary>
/// GetMaxId
/// </summary>
public int GetMaxId()
{
    return dbHelper.GetMaxID<BS_Template>("id");
}

   
获取最特别ID(当然,ID一般选拔自增,对于并发量极少的系统,或单机系统,为了省事,可以这样做):

澳门美高梅手机网站 21澳门美高梅手机网站 22

View Code

 

using System;
using System.Collections.Generic;
using System.Linq;

namespace Models
{
    /// <summary>
    /// 
    /// </summary>
    public partial class BS_Template
    {
        //暂没有扩展字段
    }
}

    补助Oracle、MSSQL、MySQL、SQLite四栽数据库,并配有Model生成器。

/// <summary>
/// 删除
/// </summary>
public void Delete(string conditions)
{
    dbHelper.Delete<BS_Template>(conditions);
}

   
我是ORM,学习成本异常低,常用的不二法门只有来多只,在利用的过程被,你不欲有无比多如留意的地点,也不谋面出“我哪些贯彻连表查询”的问号。反射牺牲局部性,不过降低了贯彻同用的复杂度。

View Code

   
例(由于是SQLite数据库,所以生成的Model没有注释,此外三种植数据库来注释):

澳门美高梅手机网站 23澳门美高梅手机网站 24

澳门美高梅手机网站 25澳门美高梅手机网站 26

View Code

   
Model生成器下载:http://files.cnblogs.com/files/s0611163/Model%E7%94%9F%E6%88%90%E5%99%A8.zip

    修改:

    根据ID删除:

澳门美高梅手机网站 27澳门美高梅手机网站 28

Model:

ExtModel:

   
不理解或者称之达成是ORM,其实就是一个DBHelper。看到网上广大口形容自己之ORM,但我当还无太好。

public BS_Test Get(string id)
{
    return dbHelper.FindById<BS_Test>(id);
}

澳门美高梅手机网站 29澳门美高梅手机网站 30

View Code

    查询列表:

澳门美高梅手机网站 31澳门美高梅手机网站 32

    代码下载:http://files.cnblogs.com/files/s0611163/DBHelperDemo.zip

澳门美高梅手机网站 33澳门美高梅手机网站 34

    SQL不可知写的乱七八糟,该换行换行,该对联合对联合,例:

try
{
    DBHelper.BeginTransaction();

    BS_Template model = new BS_Template();
    model.id = m_TemplateDal.GetMaxId().ToString();
    model.code = k.ToString("0000");
    model.name = "测试" + k.ToString();
    model.remarks = "测试" + k.ToString();
    model.type = ((int)Enums.TemplateType.Notice).ToString();
    m_TemplateDal.Insert(model);
    //throw new Exception("a");

    BS_Test test = new BS_Test();
    test.id = m_TestDal.GetMaxId().ToString();
    test.code = "测试" + k.ToString();
    test.name = "测试" + k.ToString();
    test.remarks = "测试" + k.ToString();
    m_TestDal.Insert(test);

    DBHelper.CommitTransaction();
    MessageBox.Show("成功");
}
catch (Exception ex)
{
    DBHelper.RollbackTransaction();
    MessageBox.Show(ex.Message);
}

View Code

    

澳门美高梅手机网站 35澳门美高梅手机网站 36

发表评论

电子邮件地址不会被公开。 必填项已用*标注