MinimalAPI---MinimalAPI+EFCore+IOC
作者:互联网
1.项目结构
数据库:SQL Server
项目类型:MinimalAPI
2.MinimalApi.Db类库
(1)引入相关的NuGet包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.Extensions.Logging.Console
System.Data.SqlClient
具体版本如下
(2)具体代码
数据库结构
项目结构
项目可以直接使用脚手架生成,在nuget控制台使用以下命令:
Scaffold-DbContext "Server=.;Database=MinimalAPIData;Trusted_Connection=True;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model
备注:执行前最好先把其他项目卸载(防止表类型直接建在别的项目上),执行完毕后再加载其他项目
Commodity.cs
using System; using System.Collections.Generic; namespace MinimalApi.Db.Model { public partial class Commodity { public int Id { get; set; } public int? ProductId { get; set; } public int? CategoryId { get; set; } public string? Title { get; set; } public decimal? Price { get; set; } public string? Url { get; set; } public string? ImageUrl { get; set; } } }View Code
Company.cs
using System; using System.Collections.Generic; namespace MinimalApi.Db.Model { public partial class Company { public int Id { get; set; } public string? Name { get; set; } public DateTime? CreateTime { get; set; } public int CreatorId { get; set; } public int? LastModifierId { get; set; } public DateTime? LastModifyTime { get; set; } } }View Code
NlogManager.cs
using System; using System.Collections.Generic; namespace MinimalApi.Db.Model { public partial class NlogManager { public int Id { get; set; } public string? Application { get; set; } public DateTime Logged { get; set; } public string? Lever { get; set; } public string? Message { get; set; } public string? Logger { get; set; } public string? Callsite { get; set; } public string? Exception { get; set; } } }View Code
SysUser.cs
using System; using System.Collections.Generic; namespace MinimalApi.Db.Model { public partial class SysUser { public int Id { get; set; } public string? Name { get; set; } public string? Password { get; set; } public int Status { get; set; } public string? Phone { get; set; } public string? Mobile { get; set; } public string? Address { get; set; } public string? Email { get; set; } public long? Qq { get; set; } public string? WeChat { get; set; } } }View Code
MinimalAPIDataContext.cs
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.Logging; using MinimalApi.Db.Model; namespace MinimalApi.Db { public partial class MinimalAPIDataContext : DbContext { public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); public MinimalAPIDataContext() { } public MinimalAPIDataContext(DbContextOptions<MinimalAPIDataContext> options) : base(options) { } public virtual DbSet<Commodity> Commodities { get; set; } = null!; public virtual DbSet<Company> Companies { get; set; } = null!; public virtual DbSet<NlogManager> NlogManagers { get; set; } = null!; public virtual DbSet<SysUser> SysUsers { get; set; } = null!; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //if (!optionsBuilder.IsConfigured) //{ // optionsBuilder.UseSqlServer("Server=.;Database=MinimalAPIData;Trusted_Connection=True;MultipleActiveResultSets=true;"); //} optionsBuilder.UseLoggerFactory(MyLoggerFactory); } /// <summary> /// 配置对象与数据库之间的映射关系 /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Commodity>(entity => { entity.ToTable("Commodity"); entity.Property(e => e.ImageUrl).IsUnicode(false); entity.Property(e => e.Price).HasColumnType("decimal(9, 2)"); entity.Property(e => e.Title) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Url).IsUnicode(false); }); modelBuilder.Entity<Company>(entity => { entity.ToTable("Company"); entity.Property(e => e.CreateTime).HasColumnType("datetime"); entity.Property(e => e.LastModifyTime).HasColumnType("datetime"); entity.Property(e => e.Name).HasMaxLength(100); }); modelBuilder.Entity<NlogManager>(entity => { entity.ToTable("NlogManager"); entity.Property(e => e.Application) .HasMaxLength(100) .IsUnicode(false); entity.Property(e => e.Callsite) .HasMaxLength(100) .IsUnicode(false); entity.Property(e => e.Exception).IsUnicode(false); entity.Property(e => e.Lever) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Logged).HasColumnType("datetime"); entity.Property(e => e.Logger).IsUnicode(false); entity.Property(e => e.Message).IsUnicode(false); }); modelBuilder.Entity<SysUser>(entity => { entity.ToTable("SysUser"); entity.Property(e => e.Address).HasMaxLength(100); entity.Property(e => e.Email) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Mobile) .HasMaxLength(20) .IsUnicode(false); entity.Property(e => e.Name).HasMaxLength(100); entity.Property(e => e.Password) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Phone) .HasMaxLength(20) .IsUnicode(false); entity.Property(e => e.WeChat) .HasMaxLength(100) .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }View Code
3.MininalApi.Interfaces类库
引入NuGet包 :System.Data.SqlClient
(1)IBaseService.cs
using MininalApi.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace MininalApi.Interfaces { public interface IBaseService : IDisposable { #region Query /// <summary> /// 根据id查询实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> T Find<T>(int id) where T : class; /// <summary> /// 提供对单表的查询 /// </summary> /// <typeparam name="T"></typeparam> /// <returns>IQueryable类型集合</returns> [Obsolete("尽量避免使用,using带表达式目录树的替代")] IQueryable<T> Set<T>() where T : class; /// <summary> /// 根据条件查询 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="funWhere"></param> /// <returns></returns> IQueryable<T> Query<T>(Expression<Func<T,bool>> funWhere) where T : class; PageResult<T> QueryPage<T, S>(Expression<Func<T, bool>> funcWhere,bool isAsc, Func<T, S> funOrderby,int pageIndex,int pageSize) where T : class; #endregion #region Add /// <summary> /// 新增数据,及时Commit /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns>返回带主键的实体</returns> T Insert<T>(T t) where T : class; /// <summary> /// 插入一个数据集(多条sql一个连接,事务插入) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tList"></param> /// <returns></returns> IEnumerable<T> Insert<T>(IEnumerable<T> tList) where T : class; #endregion #region Update /// <summary> /// 更新数据,及时Commit /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> void Update<T>(T t) where T : class; void Update<T>(IEnumerable<T> tList) where T : class; #endregion #region Delete /// <summary> /// 根据主键删除数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> void Delete<T>(int id) where T : class; /// <summary> /// 删除数据,及时Commit /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> void Delete<T>(T t) where T : class; void Delete<T>(IEnumerable<T> tList) where T : class; #endregion #region Other /// <summary> /// 立即保存全部修改 /// </summary> void Commit(); void ExecuteQuery<T>(string sql, Func<SqlParameter[]> parameterBuilder, Action<IList<T>> resultProcessor) where T : class; void ExecuteCommand<T>(string sql, Func<SqlParameter[]> parameterBuilder, Action resultProcessor) where T : class; ///// <summary> ///// 执行sql返回集合 ///// </summary> ///// <typeparam name="T"></typeparam> ///// <param name="sql"></param> ///// <param name="parameters"></param> ///// <returns></returns> //IQueryable<T> ExcuteQuery<T>(string sql, SqlParameter[] parameters) where T : class; ///// <summary> ///// 执行sql 无返回 ///// </summary> ///// <typeparam name="T"></typeparam> ///// <param name="sql"></param> ///// <param name="parameters"></param> //void Excute<T>(string sql, SqlParameter[] parameters) where T : class; #endregion } }View Code
(2)ICompanyService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MininalApi.Interfaces { public interface ICompanyService : IBaseService { } }View Code
4.MininalApi.Models类库
PageResult.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MininalApi.Models { public class PageResult<T> where T : class { public int TotalCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public List<T> DataList { get; set; } } }View Code
5.MinimalApi.Services类库
添加项目引用:MinimalApi.Db,MinimalApi.Interfaces
(1)BaseService.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using MinimalApi.Db; using MininalApi.Interfaces; using MininalApi.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace MininalApi.Services { public class BaseService : IBaseService { #region Identity protected MinimalAPIDataContext _context { get; private set; } public BaseService(MinimalAPIDataContext context) { _context = context; } #endregion #region Query /// <summary> /// 根据id查询实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> public T Find<T>(int id) where T : class { return _context.Set<T>().Find(id); } /// <summary> /// 提供对单表的查询 /// </summary> /// <typeparam name="T"></typeparam> /// <returns>IQueryable类型集合</returns> [Obsolete("尽量避免使用,using带表达式目录树的替代")] public IQueryable<T> Set<T>() where T : class { return _context.Set<T>(); } /// <summary> /// 根据条件查询 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="funWhere"></param> /// <returns></returns> public IQueryable<T> Query<T>(Expression<Func<T, bool>> funWhere) where T : class { if (funWhere == null) { return _context.Set<T>(); } else { return _context.Set<T>().Where<T>(funWhere); } } public PageResult<T> QueryPage<T, S>(Expression<Func<T, bool>> funcWhere, bool isAsc, Func<T, S> funOrderby, int pageIndex, int pageSize) where T : class { var list = Set<T>(); if (funcWhere != null) { list = list.Where(funcWhere); } if (isAsc) { list.OrderBy(funOrderby); } else { list.OrderByDescending(funOrderby); } PageResult<T> result = new PageResult<T>() { DataList = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(), PageIndex = pageIndex, PageSize = pageSize, TotalCount = list.Count() }; return result; } #endregion #region Add /// <summary> /// 新增数据,及时Commit /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns>返回带主键的实体</returns> public T Insert<T>(T t) where T : class { var ent = _context.Add(t).Entity; Commit(); return ent; } /// <summary> /// 插入一个数据集(多条sql一个连接,事务插入) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tList"></param> /// <returns></returns> public IEnumerable<T> Insert<T>(IEnumerable<T> tList) where T : class { _context.AddRange(tList); Commit(); return tList; } #endregion #region Update /// <summary> /// 更新数据,及时Commit /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> public void Update<T>(T t) where T : class { _context.Update(t); Commit(); } public void Update<T>(IEnumerable<T> tList) where T : class { _context.UpdateRange(tList); Commit(); } #endregion #region Delete /// <summary> /// 根据主键删除数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> public void Delete<T>(int id) where T : class { T t = Find<T>(id); if (t == null) { throw new Exception("T is null"); } _context.Remove(t); Commit(); } /// <summary> /// 删除数据,及时Commit /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> public void Delete<T>(T t) where T : class { _context.Remove(t); Commit(); } public void Delete<T>(IEnumerable<T> tList) where T : class { _context.RemoveRange(tList); Commit(); } #endregion #region Other /// <summary> /// 立即保存全部修改 /// </summary> public void Commit() { _context.SaveChanges(); } public void ExecuteQuery<T>(string sql, Func<SqlParameter[]> parameterBuilder, Action<IList<T>> resultProcessor) where T : class { SqlParameter[] parameters = null; if (parameters == null) { parameters = parameterBuilder(); } var resList = _context.Set<T>().FromSqlRaw(sql, parameters).AsNoTracking().ToList(); if (resultProcessor != null) { resultProcessor(resList); } } public void ExecuteCommand<T>(string sql, Func<SqlParameter[]> parameterBuilder, Action resultProcessor) where T : class { SqlParameter[] parameters = null; if (parameters != null) { parameters = parameterBuilder(); } _context.Set<T>().FromSqlRaw(sql, parameters); if (resultProcessor != null) { resultProcessor(); } } ///// <summary> ///// 执行sql返回集合 ///// </summary> ///// <typeparam name="T"></typeparam> ///// <param name="sql"></param> ///// <param name="parameters"></param> ///// <returns></returns> //public IQueryable<T> ExcuteQuery<T>(string sql, SqlParameter[] parameters) where T : class //{ // return null; //} ///// <summary> ///// 执行sql 无返回 ///// </summary> ///// <typeparam name="T"></typeparam> ///// <param name="sql"></param> ///// <param name="parameters"></param> //public void Excute<T>(string sql, SqlParameter[] parameters) where T : class //{ //} public void Dispose() { _context.Dispose(); } #endregion } }View Code
(2)CompanyService.cs
using Microsoft.EntityFrameworkCore; using MinimalApi.Db; using MininalApi.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MininalApi.Services { public class CompanyService : BaseService, ICompanyService { public CompanyService(MinimalAPIDataContext context) : base(context) { } } }View Code
6.MinimalApi.Demo1项目
添加Nuget包:
Autofac
Autofac.Extensions.DependencyInjection
添加项目引用:
MinimalApi.Services
(1)MyApplicationModule.cs
using Autofac; using System.Reflection; namespace MininalApi.Demo1.Utility.IOCModules { public class MyApplicationModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { Assembly interfaceAssembly = Assembly.Load("MininalApi.Interfaces"); Assembly serviceAssembly = Assembly.Load("MininalApi.Services"); builder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces().InstancePerLifetimeScope();//保证生命周期基于请求 } } }View Code
(2)CompanyApiExtensions.cs
using Microsoft.AspNetCore.Mvc; using MinimalApi.Db.Model; using MininalApi.Interfaces; namespace MininalApi.Demo1 { public static class CompanyApiExtensions { public static void CompanyApi(this WebApplication app) { app.MapPost("/Company/InsertCompany", ([FromServices] ICompanyService companyService, Company company) => { var res = companyService.Insert<Company>(company); return res; }).WithTags("Company"); app.MapGet("/Company/GetCompanyById", ([FromServices] ICompanyService companyService,int id) => { var company = companyService.Find<Company>(id); return company; }).WithTags("Company"); } } }View Code
(3)Program.cs
using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MinimalApi.Db; using MinimalApi.Db.Model; using MininalApi.Demo1; using MininalApi.Demo1.Utility.IOCModules; using MininalApi.Interfaces; using MininalApi.Services; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); //允许跨域 builder.Services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); //添加swagger builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //注册DbContext builder.Services.AddDbContext<MinimalAPIDataContext>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("MinimalAPIDatabase")); }); //整合autofac容器---整合后,通过内置容器注册的服务,autofac也可以直接创建实例 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterModule(new MyApplicationModule()); }); WebApplication app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); app.CompanyApi(); app.Run();View Code
(4)appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "MinimalAPIDatabase": "Data Source=.;Initial Catalog=MinimalAPIData;Persist Security Info=True;Integrated Security=SSPI;" }, "AllowedHosts": "*" }
7.swaggen页面
项目介绍到此结束,有需要源码的可以直接在下面留下邮箱,有啥更好的建议或者有错误的地方也欢迎留言交流
标签:set,get,MinimalAPI,System,class,---,using,IOC,public 来源: https://www.cnblogs.com/hobelee/p/16585004.html