博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Dapper.NET——轻量ORM
阅读量:6382 次
发布时间:2019-06-23

本文共 6203 字,大约阅读时间需要 20 分钟。

Dapper.NET使用

本文目录

Dapper是一款轻量级ORM工具()。如果你在小的项目中,使用Entity Framework、NHibernate 来处理大数据访问及关系映射,未免有点杀鸡用牛刀。你又觉得ORM省时省力,这时Dapper 将是你不二的选择。

1、为什么选择Dapper

  1. 轻量。只有一个文件(),编译完成之后只有120k(好象是变胖了)
  2. 速度快。Dapper的速度接近与IDataReader,取列表的数据超过了DataTable。
  3. 支持多种数据库。Dapper可以在所有Ado.net Providers下工作,包括sqlite, sqlce, firebird, oracle, MySQL, PostgreSQL and SQL Server
  4. 可以映射一对一,一对多,多对多等多种关系。
  5. 性能高。通过Emit反射IDataReader的序列队列,来快速的得到和产生对象,性能不错。
  6. 支持FrameWork2.0,3.0,3.5,4.0,4.5

2、以Dapper(4.0)为例。

2.1 在数据库中建立几张表。

CREATE TABLE [dbo].[CICUser] ( [UserId] [int] IDENTITY(1, 1) PRIMARY KEY NOT NULL, [Username] [nvarchar](256) NOT NULL, [PasswordHash] [nvarchar](500) NULL, [Email] [nvarchar](256) NULL, [PhoneNumber] [nvarchar](30) NULL, [IsFirstTimeLogin] [bit] DEFAULT(1) NOT NULL, [AccessFailedCount] [int] DEFAULT(0) NOT NULL, [CreationDate] [datetime] DEFAULT(GETDATE()) NOT NULL, [IsActive] [bit] DEFAULT(1) NOT NULL ) CREATE TABLE [dbo].[CICRole] ( [RoleId] [int] IDENTITY(1, 1) PRIMARY KEY NOT NULL, [RoleName] [nvarchar](256) NOT NULL, ) CREATE TABLE [dbo].[CICUserRole] ( [Id] [int] IDENTITY(1, 1) PRIMARY KEY NOT NULL, [UserId] [int] FOREIGN KEY REFERENCES [dbo].[CICUser] ([UserId]) NOT NULL, [RoleId] [int] FOREIGN KEY REFERENCES [dbo].[CICRole] ([RoleId]) NOT NULL )

2.2实体类。

在创建实体类时,属性名称一定要与数据库字段一一对应。

public class User    {        public User()        {            Role = new List
(); } public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public bool IsFirstTimeLogin { get; set; } public int AccessFailedCount { get; set; } public DateTime CreationDate { get; set; } public bool IsActive { get; set; } public List
Role { get; set; } } public class Role { public int RoleId { get; set; } public string RoleName { get; set; } } public class Customer { public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public bool IsFirstTimeLogin { get; set; } public int AccessFailedCount { get; set; } public DateTime CreationDate { get; set; } public bool IsActive { get; set; } public Role Role { get; set; } }

3.使用方法

3.1  一对一映射

private static void OneToOne(string sqlConnectionString)        {            List
userList = new List
(); using (IDbConnection conn = GetSqlConnection(sqlConnectionString)) { string sqlCommandText = @"SELECT c.UserId,c.Username AS UserName, c.PasswordHash AS [Password],c.Email,c.PhoneNumber,c.IsFirstTimeLogin,c.AccessFailedCount, c.CreationDate,c.IsActive,r.RoleId,r.RoleName FROM dbo.CICUser c WITH(NOLOCK) INNER JOIN CICUserRole cr ON cr.UserId = c.UserId INNER JOIN CICRole r ON r.RoleId = cr.RoleId"; userList = conn.Query
(sqlCommandText, (user, role) => { user.Role = role; return user; }, null, null, true, "RoleId", null, null).ToList(); } if (userList.Count > 0) { userList.ForEach((item) => Console.WriteLine("UserName:" + item.UserName + "----Password:" + item.Password + "-----Role:" + item.Role.RoleName + "\n")); Console.ReadLine(); } }

3.2 一对多映射

private static void OneToMany(string sqlConnectionString)        {            Console.WriteLine("One To Many"); List
userList = new List
(); using (IDbConnection connection = GetSqlConnection(sqlConnectionString)) { string sqlCommandText3 = @"SELECT c.UserId, c.Username AS UserName, c.PasswordHash AS [Password], c.Email, c.PhoneNumber, c.IsFirstTimeLogin, c.AccessFailedCount, c.CreationDate, c.IsActive, r.RoleId, r.RoleName FROM dbo.CICUser c WITH(NOLOCK) LEFT JOIN CICUserRole cr ON cr.UserId = c.UserId LEFT JOIN CICRole r ON r.RoleId = cr.RoleId"; var lookUp = new Dictionary
(); userList = connection.Query
(sqlCommandText3, (user, role) => { User u; if (!lookUp.TryGetValue(user.UserId, out u)) { lookUp.Add(user.UserId, u = user); } u.Role.Add(role); return user; }, null, null, true, "RoleId", null, null).ToList(); var result = lookUp.Values; } if (userList.Count > 0) { userList.ForEach((item) => Console.WriteLine("UserName:" + item.UserName + "----Password:" + item.Password + "-----Role:" + item.Role.First().RoleName + "\n")); Console.ReadLine(); } else { Console.WriteLine("No Data In UserList!"); } }

3.3 插入实体

public static void InsertObject(string sqlConnectionString)        {            string sqlCommandText = @"INSERT INTO CICUser(Username,PasswordHash,Email,PhoneNumber)VALUES( @UserName, @Password, @Email, @PhoneNumber )"; using (IDbConnection conn = GetSqlConnection(sqlConnectionString)) { User user = new User(); user.UserName = "Dapper"; user.Password = "654321"; user.Email = "Dapper@infosys.com"; user.PhoneNumber = "13795666243"; int result = conn.Execute(sqlCommandText, user); if (result > 0) { Console.WriteLine("Data have already inserted into DB!"); } else { Console.WriteLine("Insert Failed!"); } Console.ReadLine(); } }

3.4 执行存储过程

///         /// Execute StoredProcedure and map result to POCO        ///  ///  public static void ExecuteStoredProcedure(string sqlConnnectionString) { List
users = new List
(); using (IDbConnection cnn = GetSqlConnection(sqlConnnectionString)) { users = cnn.Query
("dbo.p_getUsers", new { UserId = 2 }, null, true, null, CommandType.StoredProcedure).ToList(); } if (users.Count > 0) { users.ForEach((user) => Console.WriteLine(user.UserName + "\n")); } Console.ReadLine(); }
///         /// Execute StroedProcedure and get result from return value        ///  ///  public static void ExecuteStoredProcedureWithParms(string sqlConnnectionString) { DynamicParameters p = new DynamicParameters(); p.Add("@UserName", "cooper"); p.Add("@Password", "123456"); p.Add("@LoginActionType", null, DbType.Int32, ParameterDirection.ReturnValue); using (IDbConnection cnn = GetSqlConnection(sqlConnnectionString)) { cnn.Execute("dbo.p_validateUser", p, null, null, CommandType.StoredProcedure); int result = p.Get
("@LoginActionType"); Console.WriteLine(result); } Console.ReadLine(); }

转载地址:http://grwha.baihongyu.com/

你可能感兴趣的文章
puremvc 笔记
查看>>
[iPad初试]系统介绍及数据交互
查看>>
[Python3网络爬虫开发实战] 4-解析库的使用
查看>>
BCS--设置BDC元数据存储权限--访问被业务数据拒绝
查看>>
骑士 字符串的相关操作与内置函数(集合)
查看>>
SEO 百度后台主动推送链接
查看>>
File 类 操作实例
查看>>
CSS中浮动的使用
查看>>
Bad Habbits
查看>>
转:不应该不知道C++的常用库
查看>>
LeetCode:Pascal's Triangle I II
查看>>
vscode plugins
查看>>
数据结构排序
查看>>
vi技巧: 宏的使用技巧(其中怎样保存宏)那部分比较重要
查看>>
angular2.0学习笔记1.开发环境搭建 (node.js和npm的安装)
查看>>
.bashrc和.bash_profile的区别
查看>>
让你的PHP程序真正的实现多线程(PHP多线程类)(转)
查看>>
Java JDBC 基础知识
查看>>
search-a-2d-matrix——二维矩阵找数
查看>>
lua基础【三】唯一数据结构table表
查看>>