Dapper 学习笔记

一、基础

1.Dapper代码就一个SqlMapper.cs文件, 前人测试Dapper速度较快 的Orm,读取速度接近IDataReader,超过DataTable。

2.a.下载地址 https://github.com/StackExchange/dapper-dot-net ,包含在线示例 (test project)。b.net 下可以通过 Nuget下载。

3.实体类用NHibernateMappingGenerator生成。

二、示例代码

1.sql脚本

USE [FactoryDeal]
GO

/****** Object:  Table [dbo].[User]    Script Date: 06/12/2015 10:57:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[User](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [LoginNo] [nvarchar](16) NOT NULL,
    [PassWord] [nvarchar](32) NOT NULL,
    [PassPort] [nvarchar](32) NULL,
    [Type] [tinyint] NULL,
    [FactoryId] [int] NULL,
    [RoleId] [int] NULL,
    [TrueName] [nvarchar](8) NULL,
    [NickName] [nvarchar](32) NULL,
    [Gender] [tinyint] NULL,
    [Company] [nvarchar](32) NULL,
    [Dept] [nvarchar](32) NULL,
    [SelfCellphone] [nvarchar](32) NULL,
    [SelfTellphone] [nvarchar](32) NULL,
    [Duty] [nvarchar](32) NULL,
    [Address] [nvarchar](64) NULL,
    [Legal] [nvarchar](32) NULL,
    [LinkMan] [nvarchar](16) NULL,
    [Cellphone] [nvarchar](32) NULL,
    [Tellphone] [nvarchar](32) NULL,
    [Fax] [nvarchar](32) NULL,
    [PostCode] [nvarchar](6) NULL,
    [Email] [nvarchar](16) NULL,
    [QQ] [nvarchar](16) NULL,
    [BusinessImgPath] [nvarchar](128) NULL,
    [TaxRegImgPath] [nvarchar](128) NULL,
    [OrgImgPath] [nvarchar](128) NULL,
    [AuthNo] [nvarchar](20) NULL,
    [ifAuth] [bit] NULL,
    [CreateTime] [datetime] NULL,
    [EditeTime] [datetime] NULL,
    [EditeMan] [nvarchar](8) NULL,
    [Status] [tinyint] NULL,
 CONSTRAINT [PK_User] 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

USE [FactoryDeal]
GO

/****** Object:  Table [dbo].[User_Module]    Script Date: 06/12/2015 11:00:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[User_Module](
    [UserId] [int] NOT NULL,
    [ModuleId] [int] NOT NULL,
 CONSTRAINT [PK_User_Module] PRIMARY KEY CLUSTERED
(
    [UserId] ASC,
    [ModuleId] 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

USE [FactoryDeal]
GO
/****** Object:  StoredProcedure [dbo].[usp_insertChatRecord]    Script Date: 06/12/2015 11:01:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[usp_insertChatRecord]
@FromLoginNo [nchar](32),
@ToLoginNo [nvarchar](32),
@Type [tinyint],
@Message [text],
@SendTime [datetime],
@Status [tinyint]
as
declare @nowYear nvarchar(4)
declare @sqlstr nvarchar(1024)
set @nowYear=CAST(DATEPART(year,GETDATE()) as nvarchar(4))
begin

  if (not exists(select object_id from sys.tables where name=‘ChatRecord_‘+@nowYear))
  begin
   set @sqlstr= ‘CREATE TABLE ChatRecord_‘[email protected]+‘(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FromLoginNo] [nchar](32) NOT NULL,
    [ToLoginNo] [nvarchar](32) NOT NULL,
    [Type] [tinyint] NULL),
    [Message] [text] NULL,
    [SendTime] [datetime] NULL,
    [Status] [tinyint] NULL) go‘
     exec sp_executesql @sqlstr
  end

  ---动态插入数据
  set @sqlstr=‘INSERT INTO ChatRecord_‘[email protected]+‘
          ([FromLoginNo]
          ,[ToLoginNo]
          ,[Type]
           ,[Message]
           ,[SendTime]
           ,[Status])
     VALUES(@FromLoginNo,@ToLoginNo,@Type,@Message ,@SendTime,@Status)‘
    exec sp_executesql @sqlstr ,N‘@FromLoginNo nchar(32),@ToLoginNo [nvarchar](32),@Type [tinyint],@Message [text],@SendTime [datetime],@Status [tinyint]‘,
    @FromLoginNo,@ToLoginNo,@Type,@Message,@SendTime,@Status

end

2.实体类

    public class User
    {
        public virtual int Id { get; set; }
        public virtual string Loginno { get; set; }
        public virtual string Password { get; set; }
        public virtual string Passport { get; set; }
        public virtual byte? Type { get; set; }
        public virtual int? Factoryid { get; set; }
        public virtual int? Roleid { get; set; }
        public virtual string Truename { get; set; }
        public virtual string Nickname { get; set; }
        public virtual byte? Gender { get; set; }
        public virtual string Company { get; set; }
        public virtual string Dept { get; set; }
        public virtual string Selfcellphone { get; set; }
        public virtual string Selftellphone { get; set; }
        public virtual string Duty { get; set; }
        public virtual string Address { get; set; }
        public virtual string Legal { get; set; }
        public virtual string Linkman { get; set; }
        public virtual string Cellphone { get; set; }
        public virtual string Tellphone { get; set; }
        public virtual string Fax { get; set; }
        public virtual string Postcode { get; set; }
        public virtual string Email { get; set; }
        public virtual string Qq { get; set; }
        public virtual string Businessimgpath { get; set; }
        public virtual string Taxregimgpath { get; set; }
        public virtual string Orgimgpath { get; set; }
        public virtual string Authno { get; set; }
        public virtual bool? Ifauth { get; set; }
        public virtual DateTime? Createtime { get; set; }
        public virtual DateTime? Editetime { get; set; }
        public virtual string Editeman { get; set; }
       // public virtual byte? Status { get; set; }

        public int MyProperty { get; set; }

        public IList<UserModule> Modules { get; set; }
    }

 public class UserModule
    {
        public virtual int Userid { get; set; }
        public virtual int Moduleid { get; set; }

        public User User { get; set; }
    }

 public class ChatRecord
    {
        public virtual string Fromloginno { get; set; }
        public virtual string Tologinno { get; set; }
        public virtual byte? Type { get; set; }
        public virtual string Message { get; set; }
        public virtual DateTime? Sendtime { get; set; }
        public virtual byte? Status { get; set; }
    }

3.Dapper方法

  private IList<User> GetAll()
        {
            string sql = "select * from [user]";

            return conn.Query<User>(sql).ToList();
        }

        private User GetSingleById(int id)
        {
            string sql = "select * from [user] where [email protected]";

            return conn.Query<User>(sql, param: new {id=id}).FirstOrDefault();
            //param 必须是对象项属性 param:id 不正确
        }

        private User Add(User user)
        {
            string sql = "insert into [user](loginNo,password) OUTPUT  inserted.Id values(@loginNo,@password)";
            user.Id=(int)conn.ExecuteScalar(sql, user);

            return user;
        }
        private bool Update(User user)
        {
            string sql = "update [user] set [email protected] where [email protected]";

            return conn.Execute(sql, user)>=1;
        }

        private bool Delete(int id)
        {
            string sql = "delete from [user] where [email protected]";

            return conn.Execute(sql, new { id = id })>=1;
        }

        //1-N
        private IList<User> GetAllUserWithModules()
        {
            string sql = "select * from [user] as a left join User_Module as b on a.Id=b.UserId";

            //保证join UserModule条数
            User user = null;

            //异常  When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id
            //必须添加 splitOn 同时查询字段必须包括外键 b.UserId
            return conn.Query<User,UserModule, User>(sql, (u, m) => {

                if (user==null||user.Id!=u.Id)
                {
                    user = u;
                }

                if (m != null)
                {
                    if (user.Modules==null)
                    {
                        user.Modules = new List<UserModule>();
                    }
                    user.Modules.Add(m);
                }

                return user;
            },splitOn:"Id,UserId").Distinct().ToList();

        }

        //1*1
        private IList<UserModule> GetAllModuleWithUser()
        {
            //inner join
            string sql = "select * from User_Module a left join [User] b on a.UserId=b.Id ";

            return conn.Query<UserModule, User, UserModule>(sql,(m, u) =>
            {
                m.User = u;
                return m;

            },"UserId,Id").ToList();
        }

        //事务
        private bool DeleteUserWithModule(int id)
        {
            string sql1 = "delete from [User] where [email protected]";
            string sql2 = "delete from User_Module where [email protected]";

            using (conn)
            {
                conn.Open();

                using (var transaction = conn.BeginTransaction())
                {
                    try
                    {
                        //Query必须添加 transaction:transaction
                        conn.Execute(sql1, new { id = id},transaction:transaction);
                        conn.Execute(sql2, new { userId = id },transaction:transaction);
                        transaction.Commit();

                        return true;
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();

                        return false;
                    }
                }
            }
        }

        private bool AdddChatRecord(ChatRecord chatRecord)
        {
            conn.Execute("usp_insertChatRecord", param: chatRecord,commandType:System.Data.CommandType.StoredProcedure);

            return true;
        }

三、总结

个人感觉dapper 在处理join实体转换,尤其是1对多方面处理起来比麻烦。有什么好的实现方式,还请各位大虾指点....

时间: 2024-08-25 01:27:24

Dapper 学习笔记的相关文章

Dapper学习笔记(一)

https://github.com/StackExchange/dapper-dot-net Dapper是对IDbConnection的扩展,需要使用Dapper提供的扩展只需要把SqlMapper这个文件放到自己的项目中即可.这样项目中的IDbConnection就可以直接使用Dapper中的扩展方法,这是怎么实现的呢?百度才知道这个是C#提供的扩展方法. 扩展方法如何使用呢?直接看代码. 对Object写一个自定义的ToString()方法,输出"自定义Object的ToString()

Dapper学习笔记(2)-链接引用

在研究Dapper源码时发现Dapper NET45类库中的SqlMapper.cs文件前面有个蓝色的箭头图标,发现在Dapper NET45文件夹下根本不存在SqlMapper.cs文件,其文件属性中的完整路径指向了Dapper NET40文件夹中的SqlMapper.cs文件,如下图: 后发现其为一个链接引用,代码文件只有一份,但是可以被多个项目所包含.在项目里面添加一个已存在的文件时选择“添加为链接”即可,具体操作如下:

Dapper学习笔记(4)-事务

Dapper中对事务的处理也非常简单,如下代码所示: 1 private void DapperTransaction() 2 { 3 using (IDbConnection con = OpenConnection()) 4 { 5 IDbTransaction tran = con.BeginTransaction(); 6 try 7 { 8 string query = "update T_Role set RoleName='开发主管' where RoleId=4";//

一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移

不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.supervisor.mysql环境搭建搭建好了.net core linux的相关环境,今天就来说说ef core相关的配置及迁移: 简介: Entity Framework(以下简称EF) 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (O/R Mapping) 解决方案,EF Core是Entity

vector 学习笔记

vector 使用练习: /**************************************** * File Name: vector.cpp * Author: sky0917 * Created Time: 2014年04月27日 11:07:33 ****************************************/ #include <iostream> #include <vector> using namespace std; int main

Caliburn.Micro学习笔记(一)----引导类和命名匹配规则

Caliburn.Micro学习笔记(一)----引导类和命名匹配规则 用了几天时间看了一下开源框架Caliburn.Micro 这是他源码的地址http://caliburnmicro.codeplex.com/ 文档也写的很详细,自己在看它的文档和代码时写了一些demo和笔记,还有它实现的原理记录一下 学习Caliburn.Micro要有MEF和MVVM的基础 先说一下他的命名规则和引导类 以后我会把Caliburn.Micro的 Actions IResult,IHandle ICondu

jQuery学习笔记(一):入门

jQuery学习笔记(一):入门 一.JQuery是什么 JQuery是什么?始终是萦绕在我心中的一个问题: 借鉴网上同学们的总结,可以从以下几个方面观察. 不使用JQuery时获取DOM文本的操作如下: 1 document.getElementById('info').value = 'Hello World!'; 使用JQuery时获取DOM文本操作如下: 1 $('#info').val('Hello World!'); 嗯,可以看出,使用JQuery的优势之一是可以使代码更加简练,使开

[原创]java WEB学习笔记93:Hibernate学习之路---Hibernate 缓存介绍,缓存级别,使用二级缓存的情况,二级缓存的架构集合缓存,二级缓存的并发策略,实现步骤,集合缓存,查询缓存,时间戳缓存

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------

Activiti 学习笔记记录(三)

上一篇:Activiti 学习笔记记录(二) 导读:上一篇学习了bpmn 画图的常用图形标记.那如何用它们组成一个可用文件呢? 我们知道 bpmn 其实是一个xml 文件