.Net Core3.0 WebApi 六: Sqlsugar+异步泛型仓储
.Net Core3.0 WebApi 目录
SqlSugar介绍
SqlSugar是国人开发者开发的一款基于.NET的ORM框架,是可以运行在.NET 4.+ & .NET CORE的高性能、轻量级 ORM框架,众多.NET框架中最容易使用的数据库访问技术。官网http://www.codeisbug.com/Doc/8
SqlSugar的优点:
1、高性能 ,不夸张的说,去掉Sql在数据库执行的时间,SqlSugar是EF数倍性能,另外在批量操作和一对多查询上也有不错的SQL优化
2、高扩展性 ,支持自定义拉姆达函数解析、扩展数据类型、支持自定义实体特性,外部缓存等
3、稳定性和技术支持, 虽然不是官方ORM, 但在稳定性上也是有着数年用户积累,如果遇到问题可以在GITHUB提出来,会根据紧急度定期解决
4、功能全面,虽然SqlSugar小巧可功能并不逊色于EF框架
5、创新、持续更新 ,向下兼容
此篇博客,我就不实际连接数据库了。写一些假数据放在这里。
Repository 和Model层中引入SqlSugar
在数据库中新建一个UserNew表格,然后再Models层中对应的实体类:
///<summary> ///用户表 ///</summary> [SugarTable("UserNew")] public partial class UserNew { /// <summary> /// Desc:用户ID /// Default: /// Nullable:False /// </summary> [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int UserId { get; set; } /// <summary> /// Desc:用户名 /// Default: /// Nullable:True /// </summary> public string UserName { get; set; } /// <summary> /// Desc:年龄 /// Default: /// Nullable:True /// </summary> public int? Age { get; set; }
在基础设施层封装一个数据库上下文:
public sealed class SugarDbContext { public static SqlSugarClient Instance //注意当前方法的类不能是静态的 public static class这么写是错误的 { get { var db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "数据库连接,放在配置文件中", DbType = DbType.SqlServer, //IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); Console.WriteLine(); }; return db; } } }
设计仓储基类接口——IBaseRepository.cs
IRepository 层中添加Base文件夹,并添加接口 IBaseRepository.cs。
namespace WebApi.Core.IRepository { /// <summary> /// 基类接口,其他接口继承该接口 /// </summary> /// <typeparam name="TEntity"></typeparam> public interface IBaseRepository<TEntity> where TEntity : class { /// <summary> /// 根据ID查询 /// </summary> /// <param name="objId"></param> /// <returns></returns> Task<TEntity> QueryByID(object objId); /// <summary> /// 添加 /// </summary> /// <param name="model"></param> /// <returns></returns> Task<bool> Add(TEntity model); /// <summary> /// 修改 /// </summary> /// <param name="model"></param> /// <returns></returns> Task<bool> Update(TEntity model); /// <summary> /// 删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> Task<bool> DeleteByIds(object[] ids); } }
继承基接口
IRepository 层中,将其他的接口,继承Base,新建IUserRepository.cs,然后将其他所有的方法都继承该基类方法
public interface IUserRepository : IBaseRepository<UserNew> { }
对仓储基接口进行实现
Repository 层中,添加Base文件夹,并添加 BaseRepository.cs 基类
namespace WebApi.Core.Repository { public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new() { /// <summary> /// 写入实体数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<bool> Add(TEntity model) { using var dbcontext = SugarDbContext.Instance; var i = await Task.Run(() => dbcontext.Insertable(model).ExecuteReturnBigIdentity()); //返回的i是long类型,这里你可以根据你的业务需要进行处理 return i > 0; } /// <summary> /// 根据ID删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public async Task<bool> DeleteByIds(object[] ids) { using var dbcontext = SugarDbContext.Instance; var i = await Task.Run(() => dbcontext.Deleteable<TEntity>().In(ids).ExecuteCommand()); return i > 0; } /// <summary> /// 根据ID查询一条数据 /// </summary> /// <param name="objId"></param> /// <returns></returns> public async Task<TEntity> QueryByID(object objId) { using var dbcontext = SugarDbContext.Instance; return await Task.Run(() => dbcontext.Queryable<TEntity>().InSingle(objId)); } /// <summary> /// 更新实体数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<bool> Update(TEntity model) { using var dbcontext = SugarDbContext.Instance; //这种方式会以主键为条件 var i = await Task.Run(() => dbcontext.Updateable(model).ExecuteCommand()); return i > 0; } } }
Repository层新建UserRepository,继承BaseRepository和IUserRepository
public class UserRepository : BaseRepository<UserNew>, IUserRepository { }
业务逻辑层基类与基接口
IService 层中添加Base文件夹,并添加接口 IBaseService.cs。
public interface IBaseServices<TEntity> where TEntity : class { /// <summary> /// 根据ID列表删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> Task<bool> DeleteByIds(object[] ids); /// <summary> /// 根据ID查询 /// </summary> /// <param name="objId"></param> /// <returns></returns> Task<TEntity> QueryByID(object objId); /// <summary> /// 添加实体 /// </summary> /// <param name="model"></param> /// <returns></returns> Task<bool> Add(TEntity model); /// <summary> /// 更新实体 /// </summary> /// <param name="model"></param> /// <returns></returns> Task<bool> Update(TEntity model); }
Service 层中添加Base文件夹,并添加接口 BaseService.cs。并添加 BaseService.cs 基类
namespace WebApi.Core.Services.Base { public class BaseServices<TEntity> : IBaseServices<TEntity> where TEntity : class, new() { public IBaseRepository<TEntity> baseDal = new BaseRepository<TEntity>(); /// <summary> /// 写入实体 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<bool> Add(TEntity model) { return await baseDal.Add(model); } /// <summary> /// 根据ID删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public async Task<bool> DeleteByIds(object[] ids) { return await baseDal.DeleteByIds(ids); } /// <summary> /// 根据ID查询 /// </summary> /// <param name="objId"></param> /// <returns></returns> public async Task<TEntity> QueryByID(object objId) { return await baseDal.QueryByID(objId); } /// <summary> /// 更新实体 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<bool> Update(TEntity model) { return await baseDal.Update(model); } } }
IService 层新建IUserService,继承BaseService
public interface IUserService : IBaseServices<UserNew> { }
Service 层新建UserService,继承BaseService和IUserService
public class UserService : BaseServices<UserNew>, IUserService { }
控制器里面新增接口:
/// <summary> /// 根据id获取数据 /// </summary> /// <param name="id">参数id</param> /// <returns></returns> [HttpGet("{id}", Name = "Get")] public async Task<IActionResult> GetUser(int id) { IUserService userService = new UserService(); UserNew user = await userService.QueryByID(id); return Ok(user); } /// <summary> /// 添加数据 /// </summary> /// <param name="user">参数user</param> /// <returns></returns> [HttpGet("{id}", Name = "Get")] public async Task<IActionResult> Add(UserNew user) { IUserService userService = new UserService(); var count = await userService.Add(user); return Ok(count); } /// <summary> /// 更新数据 /// </summary> /// <param name="user">参数user</param> /// <returns></returns> [HttpGet("{id}", Name = "Get")] public async Task<IActionResult> Update(UserNew user) { IUserService userService = new UserService(); var sucess = await userService.Update(user); return Ok(sucess); } /// <summary> /// 删除数据 /// </summary> /// <param name="ids">参数ids</param> /// <returns></returns> [HttpGet("{id}", Name = "Get")] public async Task<IActionResult> Delete(object[] ids) { IUserService userService = new UserService(); var sucess = await userService.DeleteByIds(ids); return Ok(sucess); }
仓储模式,一般使用sqlsugar的仓储就够了,http://www.donet5.com/Home/Doc?typeId=1228
接口,可自行调试。