asp.net core 系列之webapi集成Dapper的简单操作教程
Dapper也是是一种ORM框架
这里记录下,使用ASP.NET 集成 Dapper 的过程,方便自己查看
至于Dapper的特性以及操作可以参考Dapper官方文档
1.创建数据库相关
- 在Sql Server 创建一个叫做 DapperDemo 的数据库
- 再创建一个叫做 Products 的表
脚本如下
CREATE TABLE [dbo].[Products](
[ProductID] [int] IDENTITY(,) NOT NULL,
[Name] [nvarchar](max) NULL,
[Quantity] [int] NULL,
[Price] [float] NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
2.创建一个ASP.NET Web Api 项目
- 文件->新建->项目
- 选择 ASP.NET Core Web 应用 的模板,项目名 DapperDemo
- 在新的 ASP.NET Core Web 应用的页面,选择 API 模板,并确定,不要选择支持Docker
3.增加model实体
- 右击项目,新增一个Models文件夹
- 在Models文件夹下增加一个类(class),Product
public class Product
{
[Key]
public int ProductId { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
}
4.引入Dapper NuGet包
- 工具->NuGet 包管理器 -> 管理解决方案的 Nuget 包程序包
- 搜索Dapper ,并且安装
如下,安装
也可以使用 程序包管理器控制台 进行安装
Install-Package Dapper
5.使用Dapper
Dapper的使用需要下面三步:
- 使用连接字符串( connection string )创建一个 IDBConnection 对象
- 编写你自己的sql 语句
- 把 sql 语句传给 dapper
所以,操作如下
- 创建一个Repository文件夹
- 在Repository文件夹里增加一个名为 ProductRepository 的class类
代码如下
public class ProductRepository
{
private string connectionString;
public ProductRepository()
{
connectionString = @"Server=localhost;Database=DapperDemo;Trusted_Connection=true;";
} public IDbConnection Connection
{
get {
return new SqlConnection(connectionString);
}
} public void Add(Product prod)
{
using (IDbConnection dbConnection = Connection)
{
string sQuery = "INSERT INTO Products (Name, Quantity, Price)"
+ " VALUES(@Name, @Quantity, @Price)";
dbConnection.Open();
dbConnection.Execute(sQuery, prod);
}
} public IEnumerable<Product> GetAll()
{
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
return dbConnection.Query<Product>("SELECT * FROM Products");
}
} public Product GetByID(int id)
{
using (IDbConnection dbConnection = Connection)
{
string sQuery = "SELECT * FROM Products"
+ " WHERE ProductId = @Id";
dbConnection.Open();
return dbConnection.Query<Product>(sQuery, new { Id = id }).FirstOrDefault();
}
} public void Delete(int id)
{
using (IDbConnection dbConnection = Connection)
{
string sQuery = "DELETE FROM Products"
+ " WHERE ProductId = @Id";
dbConnection.Open();
dbConnection.Execute(sQuery, new { Id = id });
}
} public void Update(Product prod)
{
using (IDbConnection dbConnection = Connection)
{
string sQuery = "UPDATE Products SET Name = @Name,"
+ " Quantity = @Quantity, Price= @Price"
+ " WHERE ProductId = @ProductId";
dbConnection.Open();
dbConnection.Query(sQuery, prod);
}
}
}
这里的连接字符串是直接写在代码里的,可以根据需要自己调整
6.创建Controller
- 创建一个名为 ProductController 的类
代码如下
[Route("api/[controller]")]
public class ProductController : Controller
{
private readonly ProductRepository productRepository;
public ProductController()
{
productRepository = new ProductRepository();
}
// GET: api/values
[HttpGet]
public IEnumerable<Product> Get()
{
return productRepository.GetAll();
} // GET api/values/5
[HttpGet("{id}")]
public Product Get(int id)
{
return productRepository.GetByID(id);
} // POST api/values
[HttpPost]
public void Post([FromBody]Product prod)
{
if (ModelState.IsValid)
productRepository.Add(prod);
} // PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]Product prod)
{
prod.ProductId = id;
if (ModelState.IsValid)
productRepository.Update(prod);
} // DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
productRepository.Delete(id);
}
}
7.运行,验证是否成功
在这之前,可以手动往数据库表里加几条数据,我这里没有加,只是在Get方法里打了个断点
在浏览器中输入 https://localhost:44315/api/product
因为我数据库里没有数据,这里返回的空的
这里做记录方便查看,如有错误,欢迎指正
参考网址:
https://www.talkingdotnet.com/use-dapper-orm-with-asp-net-core/
asp.net core 系列之webapi集成Dapper的简单操作教程的更多相关文章
- asp.net core 系列之webapi集成EFCore的简单操作教程
因为官网asp.net core webapi教程部分,给出的是使用内存中的数据即 UseInMemoryDatabase 的方式, 这里记录一下,使用SQL Server数据库的方式即 UseSql ...
- asp.net core系列 38 WebAPI 返回类型与响应格式--必备
一.返回类型 ASP.NET Core 提供以下 Web API Action方法返回类型选项,以及说明每种返回类型的最佳适用情况: (1) 固定类型 (2) IActionResult (3) Ac ...
- asp.net core 2.0 webapi集成signalr
asp.net core 2.0 webapi集成signalr 在博客园也很多年了,一直未曾分享过什么东西,也没有写过博客,但自己也是汲取着博客园的知识成长的: 这两天想着不能这么无私,最近.N ...
- asp.net core系列 36 WebAPI 搭建详细示例
一.概述 HTTP不仅仅用于提供网页.HTTP也是构建公开服务和数据的API强大平台.HTTP简单灵活且无处不在.几乎任何你能想到的平台都有一个HTTP库,因此HTTP服务可以覆盖广泛的客户端,包括浏 ...
- asp.net core系列 37 WebAPI 使用OpenAPI (swagger)中间件
一.概述 在使用Web API时,对于开发人员来说,了解其各种方法可能是一项挑战.在ASP.NET Core上,Web api 辅助工具介绍二个中间件,包括:Swashbuckle和NSwag .NE ...
- asp.net core系列 77 webapi响应压缩
一.介绍 背景:目前在开发一个爬虫框架,使用了.net core webapi接口作为爬虫调用入口,在调用 webapi时发现爬虫耗时很短(1秒左右),但客户端获取响应时间却在3~4秒.对于这个问题考 ...
- asp.net core系列 61 Ocelot 构建服务发现简单示例
一.概述 Ocelot允许指定服务发现提供程序,如Consul或Eureka. 这二个中间件是用来实现:服务治理或秒服务发现,服务发现查找Ocelot正在转发请求的下游服务的主机和端口.目前Ocelo ...
- asp.net core系列 WebAPI 作者:懒懒的程序员一枚
asp.net core系列 36 WebAPI 搭建详细示例一.概述1.1 创建web项目1.2 添加模型类1.3 添加数据库上下文1.4 注册上下文1.5 添加控制器1.6 添加Get方法1.7 ...
- 【目录】asp.net core系列篇
随笔分类 - asp.net core系列篇 asp.net core系列 68 Filter管道过滤器 摘要: 一.概述 本篇详细了解一下asp.net core filters,filter叫&q ...
随机推荐
- linux使用windows磁盘,挂载共享目录
实例说明:客户两台服务器,一台web服务器(linux)只有50G,课程资源太多太大导致磁盘不够用:客户的文档服务器(windows)磁盘很大超过1T,所以产生了,将web资源使用文档服务器磁盘的想法 ...
- Linux Ubuntu 16.04 初次安装使用总结zzz
装了两天的ubuntu系统终于算是勉强能用了,来来回回装了有三四次,期间出了各种各样的毛病.但是还是被我的Google大法给治好了.为了装这个系统,算是耗了两天的时间,啥事情都没干,干耗在这上面了.所 ...
- jquery mobile 表单提交 图片/文件 上传
jquerymobile 下面 form 表单提交 和普通html没区别,最主要是 <form 要加一个 data-ajax='false' 否则 上传会失败 1 html代码 <!do ...
- Spring Webflux: Kotlin DSL [片断]
原文链接:https://dzone.com/articles/spring-webflux-kotlin-dsl-snippets 作者:Biju Kunjummen 译者:Jackie Tang ...
- 使用Spring Session实现Spring Boot水平扩展
小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...
- 第三期分享:一款很好用的api文档生成器
主要用途:生成API的文档 源码链接:https://github.com/tmcw/docbox 最近刚好在看:Trending in open source,在JS语言中,slate一直在周排行上 ...
- pip 安装mysqlclient报错OSError: mysql_config not found
执行 pip install mysqlclient 报错信息如下: [root@CentOS7-demo bin]# pip install mysqlclient Collecting mysql ...
- redis list命令操作
1.将值追加到列表 RPUSH key value [value ...]summary: Append one or multiple values to a listsince: 1.0.0 12 ...
- Java基本类型和引用类型
8种基本类型 一.4种整型 byte 1字节 -128--127 short 2 字节 -32,768 -- 32,767 ...
- 删除外部dwg中指定的块定义
本例实现删除外部图纸中指定的块定义,在外部图纸当前模型空间中是没有该块定义的块参照存在. 代码如下: void CBlockUtil::DeleteBlockDefFormOtherDwg(const ...