DapperExtensions 使用教程

 

最近搭建一个框架,使用dapper来做数据库访问,数据是sql server2012,支持多个数据库、事务、orm、ado.net原生操作方式,非常方便。

使用dapper的原因网上有很多文章说明,这里不再赘述。

这里把DapperExtensions贴出,希望能对大家有帮助。

 

代码:

#region 支持多个 sql server 数据库

//A数据库 
IRepository<TUser> repositoryA = new Repository<TUser>("Data Source = .;Initial Catalog = DbTestA;User Id = sa;Password = sql;");

//插入一条数据
TUser userA = repositoryA.Insert(new TUser() { Name = "张三" });


//B数据库
IRepository<TUser> repositoryB = new Repository<TUser>("Data Source = .;Initial Catalog = DbTestB;User Id = sa;Password = sql;");

//插入一条数据
TUser userB = repositoryB.Insert(new TUser() { Name = "张三" });
#endregion


#region 经过Repository模式封装的DapperExtensions

//插入一条记录
repositoryA.Insert(new TUser() { Name = "张三" });

//根据条件获取一条记录
repositoryA.GetModel(Predicates.Field<TUser>(f => f.Name, Operator.Eq, "张三"));

//根据id获取一条记录
repositoryA.GetModelById(10);

#endregion


#region 使用Dapper原生扩展

//Execute
int executeResult = repositoryA.DbConnection.Execute("update tuser set name=‘aaaaaa‘");

//ExecuteScalar
object obj = repositoryA.DbConnection.ExecuteScalar("select name from tuser where id=10");

//ExecuteReader
IDataReader dataReader = repositoryA.DbConnection.ExecuteReader("select * from tuser");

//IDataReader转DataTable
DataTable dataTable = dataReader.ToDataTable();

#endregion


#region 事务测试

//开启事务
IDbTransaction transaction = repositoryA.BeginTransaction();

//插入一条记录
TUser user = repositoryA.Insert(new TUser() { Name = Guid.NewGuid().ToString() }, transaction);

//删除一条记录
bool deleteResult = repositoryA.Delete(user, transaction);

//事务提交
transaction.Commit();

//事务回滚
transaction.Rollback();

#endregion

DbTestA:

USE [DbTestA]
GO
/****** Object:  Table [dbo].[TUser]    Script Date: 2019/4/30 18:52:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TUser](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](80) NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

DbTestB:

USE [DbTestB]
GO
/****** Object:  Table [dbo].[TUser]    Script Date: 2019/4/30 18:52:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TUser](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](80) NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

 

DapperExtensions 使用教程

上一篇:考研路茫茫——空调教室 强连通 双联通分量


下一篇:Android资源之图像资源(淡入淡出、嵌入)