首页 > 其他分享 >MinimalAPI---MinimalAPI+EFCore+IOC

MinimalAPI---MinimalAPI+EFCore+IOC

时间:2022-08-14 11:00:22浏览次数:56  
标签:set get MinimalAPI System class --- using IOC public

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
From: https://www.cnblogs.com/hobelee/p/16585004.html

相关文章

  • 数据结构与算法【Java】04---递归
    前言数据data结构(structure)是一门研究组织数据方式的学科,有了编程语言也就有了数据结构.学好数据结构才可以编写出更加漂亮,更加有效率的代码。要学习好数据结构就......
  • 实习-3
    需求:excel批量创建多个sheet表,并且指定命名首先在excel中sheet1表中把要命名的表名字写好:   问题:不合规范原因是新建表为自动默认创建3个sheet表,sheet1名称列中......
  • hdu7207-Find different【burnside引理】
    正题题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=7207题目大意一个序列\(a\),和它相同的序列当且仅当能通过以下操作实现相同:将\(a_1\)丢到\(a_n\),其余的向......
  • T265119 拯救公主--题解
    题目描述公主索菲亚被关在一个有大小一样的方格构成的四四方方的迷宫里面,索菲亚就站在其中一个方格子上,拯救方案是这样的:要用一些地砖把公主所在的方格子之外的格子都铺上......
  • 2022-8-14 剑指offer-二叉树递归
    剑指OfferII049.从根节点到叶节点的路径数字之和难度中等34收藏分享切换为英文接收动态反馈给定一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 ......
  • 【2022-08-13】何太做到了
    20:00人只有已经做了他自己能够做的一切以后,对于那些仍然要来到的东西才只好认为是不可避免的,只好平静地、无可奈何地接受它。这才是儒家所讲的“知命”的意思。  ......
  • 读取mini-imagnet图片并将其转为可迭代对象训练神经网络
    da=torchvision.transforms.Compose([torchvision.transforms.ToTensor()])#必须有这步否则会出现default_collate:batchmustcontaintensors,numpyarrays,numbers......
  • PDMS-螺栓计算
    PDMS-螺栓计算[email protected],PDMS,三维管道设计软件,三维工厂设计软件,三维配管软件1PDMS螺栓概述在PDMS中螺栓数据是通过计算得到的,因为没有对螺......
  • 爬虫数据分析-Xpath
    1.环境安装:-pipinstalllxml2.如何实例化一个etree对象:fromlxmlimportetree(1)将本地的html文档中的源码数据加载到etree对象中:etree.parse(filePath)(2)可......
  • ABC 264 C - Matrix Reducing(思维)
    https://atcoder.jp/contests/abc264/tasks/abc264_c题目大意:给定n*m的a矩阵,x*y的b矩阵问能不能删除若干行和列使a变成b?SampleInput14512345678910......