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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM