NetCore+Dapper WebApi架构搭建:底层封装

Posted Frank_520

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NetCore+Dapper WebApi架构搭建:底层封装相关的知识,希望对你有一定的参考价值。

看下我们上一节搭建的架构,现在开始从事底层的封装

1、首先需要一个实体的接口IEntity

namespace Dinner.Dapper
{
    public interface IEntity<TPrimaryKey>
    {
        TPrimaryKey Id { get; set; }
    }
}

 

2、由于所有的数据库实体都是有主键的,所以这里定义一个BaseModel,这里我用的主键是Guid,你们可以换成int

using System;

namespace Dinner.Dapper
{
    public class BaseModel : IEntity<Guid>
    {
        public Guid Id { get; set; }
    }
}

 

3、接下来是封装Dapper的SqlServer配置DataBaseConfig(Redis的配置你们可以忽略),不要忘记添加Dapper的Nuget包

using StackExchange.Redis;
using System.Data;
using System.Data.SqlClient;

namespace Dinner.Dapper
{
    public class DataBaseConfig
    {
        #region SqlServer链接配置

        private static string DefaultSqlConnectionString = @"Data Source=localhost;Initial Catalog=Dinner;User ID=sa;Password=123456;";
        private static string DefaultRedisString = "localhost, abortConnect=false";
        private static ConnectionMultiplexer redis;

        public static IDbConnection GetSqlConnection(string sqlConnectionString = null)
        {
            if (string.IsNullOrWhiteSpace(sqlConnectionString))
            {
                sqlConnectionString = DefaultSqlConnectionString;
            }
            IDbConnection conn = new SqlConnection(sqlConnectionString);
            conn.Open();
            return conn;
        }

        #endregion

        #region Redis链接配置

        private static ConnectionMultiplexer GetRedis(string redisString = null)
        {
            if (string.IsNullOrWhiteSpace(redisString))
            {
                redisString = DefaultRedisString;
            }
            if (redis == null || redis.IsConnected)
            {
                redis = ConnectionMultiplexer.Connect(redisString);
            }
            return redis;
        }

        #endregion
    }
}

 

4、然后是仓储基接口IRepositoryBase,添加了基本的增删改查和一个无参的存储过程

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Dinner.Dapper
{
    public interface IRepositoryBase<T>
    {
        Task Insert(T entity, string insertSql);

        Task Update(T entity, string updateSql);

        Task Delete(Guid Id, string deleteSql);

        Task<List<T>> Select(string selectSql);

        Task<T> Detail(Guid Id, string detailSql);

        /// <summary>
        /// 无参存储过程
        /// </summary>
        /// <param name="SPName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        Task<List<T>> ExecQuerySP(string SPName);
    }
}

 

5、仓储基实现类RepositoryBase继承仓储基接口,简单实现增删改查和无参的存储过程

 1 using Dapper;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data;
 5 using System.Linq;
 6 using System.Threading.Tasks;
 7 
 8 namespace Dinner.Dapper
 9 {
10     public class RepositoryBase<T> : IRepositoryBase<T>
11     {
12         public async Task Delete(Guid Id, string deleteSql)
13         {
14             using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
15             {
16                 await conn.ExecuteAsync(deleteSql, new { Id = Id });
17             }
18         }
19 
20         public async Task<T> Detail(Guid Id, string detailSql)
21         {
22             using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
23             {
24                 //string querySql = @"SELECT Id, UserName, Password, Gender, Birthday, CreateDate, IsDelete FROM dbo.Users WHERE Id=@Id";
25                 return await conn.QueryFirstOrDefaultAsync<T>(detailSql, new { Id = Id });
26             }
27         }
28 
29         /// <summary>
30         /// 无参存储过程
31         /// </summary>
32         /// <param name="SPName"></param>
33         /// <returns></returns>
34         public async Task<List<T>> ExecQuerySP(string SPName)
35         {
36             using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
37             {
38                 return await Task.Run(() => conn.Query<T>(SPName, null, null, true, null, CommandType.StoredProcedure).ToList());
39             }
40         }
41 
42         public async Task Insert(T entity, string insertSql)
43         {
44             using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
45             {
46                 await conn.ExecuteAsync(insertSql, entity);
47             }
48         }
49 
50         public async Task<List<T>> Select(string selectSql)
51         {
52             using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
53             {
54                 //string selectSql = @"SELECT Id, UserName, Password, Gender, Birthday, CreateDate, IsDelete FROM dbo.Users";
55                 return await Task.Run(()=>conn.Query<T>(selectSql).ToList());
56             }
57         }
58 
59         public async Task Update(T entity, string updateSql)
60         {
61             using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
62             {
63                 await conn.ExecuteAsync(updateSql, entity);
64             }
65         }
66     }
67 }

 

 

上面这些就是底层基本的封装,下一节我们来添加实体和仓储

源码地址: https://github.com/wangyulong0505/Dinner

 

来源:https://www.cnblogs.com/wangyulong/p/8961061.html

以上是关于NetCore+Dapper WebApi架构搭建:底层封装的主要内容,如果未能解决你的问题,请参考以下文章

NetCore+Dapper WebApi架构搭建:底层封装

NetCore+Dapper WebApi架构搭建:底层封装

NetCore+Dapper WebApi架构搭建:仓储的依赖注入

NetCore+Dapper WebApi架构搭建:仓储的依赖注入

NetCore+Dapper WbpApi架构搭建:底层封装

42岁大龄程序员的迷茫,看我最新尝鲜.net 5+Dapper搭建的WebAPI框架