.net Core EF 3.1 仓储模式架构搭建
什么是依赖注入,为什么要使用呢?简单通俗说就是一个类需要另一个类来协助工作,就产生了依赖,所以需要的依赖项就要【注入】过来一起来协同完成工作。
引入依赖注入的目的是为了解耦。说白了就是面向接口编程,通过调用接口的方法,而不直接实例化对象去调用。
一:创建一个 Asp.net Core Web ApI项目
添加领域层和实体层
在实体层配置数据库连接,反向工程,上结中有介绍
这个时候会报很多错误,是因为没有找到命名空间,在这里我们在实体层依赖
添加好之后,用实体层依赖领域模型
修改模板,修改成我们需要的模板
修改好后,重新编译一遍反向工程。
现在看着就精简很多了
配置连接数据库
"ConnectionStrings": { "DefaultConnection": "Data Source=.;Initial Catalog=Dispatch;Integrated Security=True" }
services.AddDbContext<DispatchContext>(budr => budr.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
现在其实已经可以在接口中写构造函数,来处理数据了。
我们要搭建的是仓储模式,所有我们还需要包一层
在实体层添加BaseRepository 上下文
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace SW163.EntityFrameworkCore { public class BaseRepository<T> where T : class, new() { public DispatchContext db; /// <summary> /// 增(异步) /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual async Task<T> AddAsync(T entity) { db.Set<T>().Add(entity); await db.SaveChangesAsync(); return entity; } /// <summary> /// 增 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual T Add(T entity) { db.Set<T>().Add(entity); db.SaveChanges(); return entity; } /// <summary> ///删除一条实体数据(异步) /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual async Task<bool> DelAsync(T entity) { db.Entry(entity).State = EntityState.Deleted; int i = await db.SaveChangesAsync(); return i > 0; } /// <summary> /// 删除一条实体数据 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual bool Del(T entity) { db.Entry(entity).State = EntityState.Deleted; int i = db.SaveChanges(); return i > 0; } /// <summary> /// 删除多条数据,根据传进来的id数据删除(异步) /// </summary> /// <param name="ids"></param> /// <returns></returns> public virtual async Task<bool> DelByIdsAsync(params int[] ids) { foreach (int id in ids) { var entity = db.Set<T>().Find(id);//如果实体已经在内存中则直接从内存中拿,否则才查询数据库 db.Set<T>().Remove(entity); } int i = await db.SaveChangesAsync(); return i > 0; } /// <summary> /// 删除多条数据,根据传进来的id数据删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public virtual bool DelByIds(params int[] ids) { foreach (int id in ids) { var entity = db.Set<T>().Find(id);//如果实体已经在内存中则直接从内存中拿,否则才查询数据库 db.Set<T>().Remove(entity); } int i = db.SaveChanges(); return i > 0; } /// <summary> /// 改(异步) /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual async Task<bool> EditAsync(T entity) { db.Entry(entity).State = EntityState.Modified; int i = await db.SaveChangesAsync(); return i > 0; } /// <summary> /// 改 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual bool Edit(T entity) { db.Entry(entity).State = EntityState.Modified; int i = db.SaveChanges(); return i > 0; } /// <summary> /// 查-获取单条数据(异步) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public virtual async Task<T> GetEntityAsync(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda) { return await db.Set<T>().Where(whereLambda).FirstOrDefaultAsync(); } /// <summary> /// 查-获取单条数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public virtual T GetEntity(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda) { return db.Set<T>().Where(whereLambda).FirstOrDefault(); } /// <summary> /// 查-获取多条数据,返回list集合(异步) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public virtual async Task<List<T>> GetListEntitiesAsync(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda) { return await db.Set<T>().Where(whereLambda).ToListAsync(); } /// <summary> /// 查-获取多条数据,返回list集合 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public virtual List<T> GetListEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda) { return db.Set<T>().Where(whereLambda).ToList(); } /// <summary> /// 查询-分页(异步) /// </summary> /// <typeparam name="s"></typeparam> /// <param name="pageIndex">第几页</param> /// <param name="pageSize">每页多少条</param> /// <param name="whereLambda">过滤数据的Lambda表达式</param> /// <param name="orderbyLambda">按照哪个排序</param> /// <param name="isAsc">是否升序排序:true升序、false降序</param> /// <returns></returns> public async Task<List<T>> GetPageListAsync<s>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc) { List<T> list = null; if (isAsc)//升序 { list = await db.Set<T>().Where(whereLambda).OrderBy(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); } else//降序 { list = await db.Set<T>().Where(whereLambda).OrderByDescending(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); } return list; } /// <summary> /// 查询-分页 /// </summary> /// <typeparam name="s"></typeparam> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="whereLambda"></param> /// <param name="orderbyLambda"></param> /// <param name="isAsc"></param> /// <returns></returns> public List<T> GetPageList<s>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc, out int totalCount) { List<T> list = null; totalCount = db.Set<T>().Where(whereLambda).Count(); if (isAsc)//升序 { list = db.Set<T>().Where(whereLambda).OrderBy(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } else//降序 { list = db.Set<T>().Where(whereLambda).OrderByDescending(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } return list; } /// <summary> /// 获取总条数(异步) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<int> GetTotalCountAsync(Expression<Func<T, bool>> whereLambda) { return await db.Set<T>().Where(whereLambda).CountAsync(); } } }
添加基础设施层:Infrastructure
领域层引用
在基础设施层添加基接口
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace SW163.Infrastructure { /// <summary> /// 基接口,操作数据库常用方法:增 删 改 查 分页 /// </summary> /// <typeparam name="T"></typeparam> public interface IRepository<T> where T : class, new() { /// <summary> /// 增(异步) /// </summary> /// <param name="entity"></param> /// <returns></returns> Task<T> AddAsync(T entity); /// <summary> /// 增 /// </summary> /// <param name="entity"></param> /// <returns></returns> T Add(T entity); /// <summary> /// 删除一条数据(异步) /// </summary> /// <param name="entity"></param> /// <returns></returns> Task<bool> DelAsync(T entity); /// <summary> /// 删 /// </summary> /// <param name="entity"></param> /// <returns></returns> bool Del(T entity); /// <summary> /// 删除多条数据(异步)-根据传进来的id数据删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> Task<bool> DelByIdsAsync(params int[] ids); /// <summary> /// 删除多条数据-根据传进来的id数据删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> bool DelByIds(params int[] ids); /// <summary> /// 改(异步) /// </summary> /// <param name="entity"></param> /// <returns></returns> Task<bool> EditAsync(T entity); /// <summary> /// 改 /// </summary> /// <param name="entity"></param> /// <returns></returns> bool Edit(T entity); /// <summary> /// 查-获取单条数据(异步) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<T> GetEntityAsync(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda); /// <summary> /// 查-获取单条数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> T GetEntity(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda); /// <summary> /// 查-获取多条数据,返回list集合(异步) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<List<T>> GetListEntitiesAsync(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda); /// <summary> /// 查-获取多条数据,返回list集合 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> List<T> GetListEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda); /// <summary> /// 查询-分页(异步) /// </summary> /// <typeparam name="s">排序字段的类型</typeparam> /// <param name="pageIndex">第几页</param> /// <param name="pageSize">每页显示多少条</param> /// <param name="whereLambda">过滤条件lambda</param> /// <param name="orderbyLambda">排序字段</param> /// <param name="isAsc">是否升序 true升序 false降序</param> /// <returns></returns> Task<List<T>> GetPageListAsync<s>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc); /// <summary> /// 查询-分页 /// </summary> /// <typeparam name="s">排序字段的类型</typeparam> /// <param name="pageIndex">第几页</param> /// <param name="pageSize">每页显示多少条</param> /// <param name="whereLambda">过滤条件lambda</param> /// <param name="orderbyLambda">排序字段</param> /// <param name="isAsc">是否升序 true升序 false降序</param> /// <param name="totalCount">返回的总记录数</param> /// <returns>返回实体集合</returns> List<T> GetPageList<s>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc, out int totalCount); /// <summary> /// 获取总记录数(异步) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<int> GetTotalCountAsync(Expression<Func<T, bool>> whereLambda); } }
添加仓储和实现文件夹
using SW163.Infrastructure; using System; using System.Collections.Generic; using System.Text; namespace SW163.Domain.IRepository { public interface IAdministratorRepository : IRepository<Administrator> { } }
using SW163.Domain; using SW163.Domain.IRepository; using System; using System.Collections.Generic; using System.Text; namespace SW163.EntityFrameworkCore.Repository { public class AdministratorRepository : BaseRepository<Administrator>, IAdministratorRepository { /// <summary> /// 构造函数注入DispatchContext上下文 /// </summary> /// <param name="dispatchContext"></param> public AdministratorRepository(DispatchContext dispatchContext) { db = dispatchContext; } } }
如果每个仓储都需要注入services.AddScoped<IAdministratorRepository, AdministratorRepository>(); 那就太繁琐了,我们这使用批量注入 Autofac.Extensions.DependencyInjection
using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SW163.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SW163.Web { public class Program { public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(budr => budr.UseStartup<Startup>()) .UseServiceProviderFactory(cntx => new AutofacServiceProviderFactory(budr => budr .RegisterAssemblyTypes(typeof(DispatchContext).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope())); } }
添加一个接口,看看配置OK没
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SW163.Domain.IRepository; using SW163.EntityFrameworkCore; using System.Threading.Tasks; namespace SW163.Web.Controllers { public class HomeController : ControllerBase { //ctor public HomeController(IAdministratorRepository administratorRepository) { AdministratorRepository = administratorRepository; } public IAdministratorRepository AdministratorRepository { get; } [HttpGet,Route("api/GetListEntity")] public async Task<ActionResult> GetListEntity() { var entity =await AdministratorRepository.GetListEntitiesAsync(it=>true); return Ok(entity); } } }
数据是展示出来了,但接口不是特别美观,我们配置swwager中间件 Swashbuckle.AspNetCore
ConfigureServices:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Repository API", Version = "v1" }); #region var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "WebApi.xml"); c.IncludeXmlComments(xmlPath, true); #endregion });
Configure:
app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Repository API V1"); });
修改启动项:
运行效果
加油