Dapper的介绍和使用

目录

概述

2.准备工作

3.使用Dapper访问数据库

4.小节


 

  1. 概述

一般而言,我们在使用dotnet 技术站时,涉及到数据库层面,往往会选择EFcore 或者Nhibernate,它们好是好,但是当你的项目比较小的时候,用这些会有一种杀鸡用牛刀的感觉,因为无论是EFcore还是Nhibernate都是比较大型的工具。这时使用Dapper就很符合你的需求了。

Dapper是.Net的简单对象映射器(ORM),可以高效的操作数据库,与EFcore 侧重点不同,它提供更加高效的数据库操作,,EF core则提供更加全能的操作。此外,Dapper是开源的,源代码在Github‘上。

Dapper没有特定的数据库的能实现细节,他可以在所有ADO.Net提供程序上使用,包括,SQlite、SQLCE、Firebird、Oracle、Mysql、SqlServer和PostgreSQL。

本文介绍基于数据库是Mysql。

2.准备工作

建立数据库,这里我直接使用WorkBench建立了一个数据库:取名为DapperExample,然后建立了一张表,

表根据如下模型构建:

public class Employee
{
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public decimal Salary { get; set; }
}

table 的设置如下:

Dapper的介绍和使用_第1张图片

创建完成后,随机添加几条数据,方便测试,

Dapper的介绍和使用_第2张图片

当然你也可以使用代码创建表并添加数据。类似于下面:

public static void CreateDatabase()
		{
			using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
			{
				connection.Open();
				using (var command = connection.CreateCommand())
				{
					command.CommandText = @"   
CREATE TABLE [dbo].[Customers] (
    [CustomerID] INT            IDENTITY (1, 1) NOT NULL,
    [FirstName]  NVARCHAR (MAX) NULL,
    [LastName]   NVARCHAR (MAX) NULL,
    [Email]      NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_dbo.Customers] PRIMARY KEY CLUSTERED ([CustomerID] ASC)
);

INSERT INTO Customers (FirstName, LastName, Email) Values ('Carson', 'Alexander', '[email protected]');
INSERT INTO Customers (FirstName, LastName, Email) Values ('Meredith', 'Alonso', '[email protected]');
INSERT INTO Customers (FirstName, LastName, Email) Values ('Arturo', 'Anand', '[email protected]');
INSERT INTO Customers (FirstName, LastName, Email) Values ('Gytis', 'Barzdukas', '[email protected]');
INSERT INTO Customers (FirstName, LastName, Email) Values ('Yan', 'Li', '[email protected]');
";
					command.ExecuteNonQuery();
				}
			}
		}

接下来创建一个基于Netcore的控制台应用程序,我取名为DapperExample。然后添加一个Model文件夹,再往文件夹添加一个类,就是刚刚显示的Employee类。因为我们使用的是MySql数据,所有还要添加几个Nuget包:

分别是:Mysql.Data、Dapper.

Dapper的介绍和使用_第3张图片

3.使用Dapper访问数据库

在Main函数连接数据库,并使用增删查改:

 class Program
    {
        static string connectString = "server=127.0.0.1;port=3306;user=root;password=abcd1992qyl; database=DapperExample;";

        static void Main(string[] args)
        {
            
            using( var Con=new MySqlConnection(connectString))
            {
                //新增数据
                Employee employee = new Employee { Id = 12, Name = "胡歌", Address = "上海市浦东新区南京路", Salary = 2233, Age = 22 };
                Insert(Con, employee);
                employee.Salary += 10000;
                Update(Con, employee);
                Delete(Con, 1);
                var ans=SearchFirstById(Con, 9);
                ans.Show();
                //Con.Open();
                //var ans2 = Get(Con,12);
                //ans2.Show();
            }

           // Console.WriteLine("Hello World!");
        }

其中Insert、Delete、Update、Query分别写成了一个函数:

 //插入一条数据
        public static void Insert(MySqlConnection connection,Employee employee)
        {
            string insetSql = "insert into employee(Id,Name,Age,Address,Salary) values (@Id,@Name,@Age,@Address,@Salary);";
            connection.Execute(insetSql, employee);
        }
        //更新一条数据
        public static void Update(MySqlConnection connection,Employee employee)
        {
            string updateSql = "update employee set salary=@Salary where Id=@Id;";
            connection.Execute(updateSql, employee);
        }
        //删除一条数据
        public static void Delete(MySqlConnection connection,int Id)
        {
            string deleteSql = "delete from employee where Id=@Id;";
            connection.Execute(deleteSql, new { Id = Id });
        }
        //查询满足条件的第一个Item
        public static Employee SearchFirstById(MySqlConnection connection,int Id,string TableName="Employee")
        {
            string select = $"SELECT * FROM {TableName} WHERE Id = {Id};";
            return connection.QueryFirst(select);
        }
        //带有异常的处理的查询
        public static Employee SearchSingle(MySqlConnection connection,string selection)
        {
            return connection.QuerySingle(selection);
        }
        //查询满足条件的所有Items
        public static List SearchMany(MySqlConnection connection,string selection)
        {
            return connection.Query(selection).AsList();
        }
        //一次执行多条语句
        public static void SearchByMutipleSelection(MySqlConnection connection,string selections)
        {
            var muti= connection.QueryMultiple(selections);
            var employee = muti.Read().First();
            var employees = muti.Read().ToList();
        }

Dapper的查询有很多函数,而且都有异步的,可以看到Dapper使用的是SQL语句来实现CURD,因此效率会很高,但是这样也有个麻烦,对于不熟悉SQL语句的,写起来会比较麻烦。于是Dapper又扩展了它的包,也就是我Nuget中的Dapper.Contrib,使用它可以实现跟简单的CURD。

要使用上面的包,首先需要对Employee模型添加注释:

using System;
using Dapper.Contrib.Extensions;

namespace DapperExample.Model
{
    [Table("Employee")]
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        [Write(true)]
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public decimal Salary { get; set; }

        public Employee()
        {
        }

        public void Show()
        {
            Console.WriteLine($"Id: {Id}\t Name: {Name}\t Age: {Age} \t Address: {Address} \t Salary: {Salary}");
        }
    }
}
  • Table:指定实体对应地数据库表名,可忽略,但是忽略后实体对应地数据库表名会在末尾加个s,Demo对应Demos(感觉画蛇添足了)
  • Key:指定此列为主键(自动增长主键),可忽略,忽略后默认查找
  • ExplicitKey:指定此列为主键(不自动增长类型例如guid,ExplicitKey与Key地区别下面会详细讲)
  • Computed:计算属性,打上此标签,对象地insert,update等操作会忽略此列
  • Write:需穿一个bool值,false时insert,update等操作会忽略此列

其中主要要设置的是Table和Key,其它设置一般可以不用设置。

设置之后,CURD可以写成这样:

        public static Employee Get(MySqlConnection con,int Id)
        {
            return con.Get(Id);
        }
        public static List GetAll(MySqlConnection con)
        {
            return con.GetAll().ToList();
        }
        public static void Insert(MySqlConnection con,List employees)
        {
            con.Insert(employees);
        }
        public static void Update(MySqlConnection con,List employees)
        {
            con.Update(employees);
        }
        public static void Delete(MySqlConnection con,List employees)
        {
            con.Delete(employees);
        }
        public static void DeleteAll(MySqlConnection con)
        {
            con.DeleteAll();
        }

可以看到,CURD不用再写SQL语句了。在Main中使用如下:

                 Con.Open();               
                var ans2 = Get(Con, 12);
               ans2.Show();
                ans2.Name = "Sanfu";//"独孤无敌";
                Update(Con,new List { ans2});
                var ans2_new = Get(Con, 12);
                ans2_new.Show();

需要注意的所有操作之前,需要加上Con.Open().


4.小节

可以看到使用Dapper实现对数据库的访问确实比较容易,Dapper官网有详细的说明文档,遇到问题建议去官网查询。这里的项目只是一个控制台项目,你也可以再Asp.net core中使用。

 

你可能感兴趣的:(数据库,Dapper,C#)