Dapper 学习笔记
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(,) NOT NULL,
[LoginNo] [nvarchar]() NOT NULL,
[PassWord] [nvarchar]() NOT NULL,
[PassPort] [nvarchar]() NULL,
[Type] [tinyint] NULL,
[FactoryId] [int] NULL,
[RoleId] [int] NULL,
[TrueName] [nvarchar]() NULL,
[NickName] [nvarchar]() NULL,
[Gender] [tinyint] NULL,
[Company] [nvarchar]() NULL,
[Dept] [nvarchar]() NULL,
[SelfCellphone] [nvarchar]() NULL,
[SelfTellphone] [nvarchar]() NULL,
[Duty] [nvarchar]() NULL,
[Address] [nvarchar]() NULL,
[Legal] [nvarchar]() NULL,
[LinkMan] [nvarchar]() NULL,
[Cellphone] [nvarchar]() NULL,
[Tellphone] [nvarchar]() NULL,
[Fax] [nvarchar]() NULL,
[PostCode] [nvarchar]() NULL,
[Email] [nvarchar]() NULL,
[QQ] [nvarchar]() NULL,
[BusinessImgPath] [nvarchar]() NULL,
[TaxRegImgPath] [nvarchar]() NULL,
[OrgImgPath] [nvarchar]() NULL,
[AuthNo] [nvarchar]() NULL,
[ifAuth] [bit] NULL,
[CreateTime] [datetime] NULL,
[EditeTime] [datetime] NULL,
[EditeMan] [nvarchar]() 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](),
@ToLoginNo [nvarchar](),
@Type [tinyint],
@Message [text],
@SendTime [datetime],
@Status [tinyint]
as
declare @nowYear nvarchar()
declare @sqlstr nvarchar()
set @nowYear=CAST(DATEPART(year,GETDATE()) as nvarchar())
begin if (not exists(select object_id from sys.tables where name='ChatRecord_'+@nowYear))
begin
set @sqlstr= 'CREATE TABLE ChatRecord_'+@nowYear+'(
[Id] [int] IDENTITY(,) NOT NULL,
[FromLoginNo] [nchar]() NOT NULL,
[ToLoginNo] [nvarchar]() 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_'+@nowYear+'
([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 id=@id"; 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 loginNo=@loginNo where id=@id"; return conn.Execute(sql, user)>=;
} private bool Delete(int id)
{
string sql = "delete from [user] where id=@id"; return conn.Execute(sql, new { id = id })>=;
} //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 id=@id";
string sql2 = "delete from User_Module where userId=@userId"; 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对多方面处理起来比麻烦。有什么好的实现方式,还请各位大虾指点....
Dapper 学习笔记的更多相关文章
- Dapper学习笔记(1)-开始
Dapper是一款开源的轻量级ORM工具,源代码下载地址为https://github.com/StackExchange/dapper-dot-net,其具有以下特点: 1.Dapper是一个轻型的 ...
- Dapper学习笔记(一)
https://github.com/StackExchange/dapper-dot-net Dapper是对IDbConnection的扩展,需要使用Dapper提供的扩展只需要把SqlMappe ...
- Dapper学习笔记(4)-事务
Dapper中对事务的处理也非常简单,如下代码所示: private void DapperTransaction() { using (IDbConnection con = OpenConnect ...
- Dapper学习笔记(2)-链接引用
在研究Dapper源码时发现Dapper NET45类库中的SqlMapper.cs文件前面有个蓝色的箭头图标,发现在Dapper NET45文件夹下根本不存在SqlMapper.cs文件,其文件属性 ...
- [C#]Dapper学习笔记
1.安装,直接用nuget搜索Dapper就行,不过只支持框架4.5.1 2.数据库测试表 CREATE TABLE [dbo].[Student]( [ID] [bigint] NULL, ) NU ...
- Dapper学习笔记
听说有个轻量化的orm Dapper,我就去了解下.试着对Sql Server和Mysql进行增删改查,体验不错.它不如EF臃肿,也比一般的封装灵活,比如我们封装了一个映射类.利用反射,在Execut ...
- Dapper学习笔记(5)-存储过程
一.无参存储过程 第一步:创建一个不带参数的存储过程,代码如下: CREATE PROCEDURE [dbo].[QueryRoleNoParms] AS BEGIN SELECT * FROM T_ ...
- Dapper学习笔记(3)-增、删、改、查
一.建表 在数据库中建立如下三张表: CREATE TABLE [dbo].[T_User] ( , ) PRIMARY KEY NOT NULL, ) NOT NULL, ) NULL, ) NUL ...
- 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移
不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...
随机推荐
- Laravel5 构造器高级查询条件写法
<?php #DB 高级查询 // select * from table where A and B or C $all_data = DB::table("shopnc_goods ...
- Mac 中显示资源库(Library)文件夹目录的几种方法
Mac中Library目录在10.6.7系统之后默认隐藏的,要想找到此文件夹有如下几种方法: 1. 用命令可以使其显示: 在终端中执行命令: chflags nohidden ~/Library ...
- B4260 Codechef REBXOR
真是6块钱cpu(笑 爆炸入口 踹树练习(汗 对于二进制异或和弹性,我们可以贪心的来做. 瓶颈在于快速贪心. 我们可以维护一个trie树,储存异或前缀和.每次在trie树上贪心的跑. 正向and反向跑 ...
- CUDA内存拷贝
原文链接1.cudaMemcpy()<--> cudaMalloc() //线性内存拷贝 1 //线性内存拷贝 2 cudaMalloc((void**)&dev_A, data ...
- <strong>和 <b> 的区别
前几天,看到这样的一个笑话:甲:“我精通前端开发”,乙:“strong和b的区别是什么?” 甲:.... 其实我也搞不清有什么区别,因此我整理了一下: 一.为什么会有这样一个问题 我们在一个没有附加式 ...
- C#中datatable的用法/传数据
在开发中,我们常用到表类型数据,不同于string,int....那么datatable类型如何定义呢,具体怎么使用呢,代码如下: namespace Common.Table { using Sys ...
- Java对象容器总结
泛型容器类 容器类型: ArrayList 元素类型: 有排序 String:里面存放的是对象的管理者,而不是具体的对象,所以string类型有null值 集合容器 容器类型 Set 元素类型 唯一性 ...
- bootloader 关闭看门狗
#define pWTCON 0x53000000disable_watchdog: ldr r0, =pWTCON mov r1, #0x0 str r1, [r0]
- Java web--过滤器
本文引自:https://www.cnblogs.com/dudududu/p/8505177.html 参考博客:http://www.cnblogs.com/coderland/p/5902878 ...
- 简单了解,使用oracle中的索引,表分区
索引的分类 如下: 物理分类 逻辑分类 分区或非分区索引 单列或组合索引 B树索引(标准索引) 唯一或非唯一索引 正常或反向键索引 基于函数索引 位图索引 B树索引 b树索引通常也称为标准索引,索 ...