WebApi+sqlsugar+仓储模式

WebApi+sqlsugar+仓储模式学习记录

  • 1.创建模板
  • 2.填写项目名称保存位置
  • 3.打钩OpenAPI会自动配置swagger
  • 4.创建仓储,服务文件夹,Model层,添加类库
  • 5.安装sqlsugar包
  • 6.贴上代码
  • 7.效果示例

前言:因为要做uni-app小程序的项目,所以后端用这个来做,小程序链接: uni-app商城

1.创建模板

WebApi+sqlsugar+仓储模式_第1张图片

2.填写项目名称保存位置

WebApi+sqlsugar+仓储模式_第2张图片

3.打钩OpenAPI会自动配置swagger

WebApi+sqlsugar+仓储模式_第3张图片
Startup

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "UniShop.Api v1"));
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

4.创建仓储,服务文件夹,Model层,添加类库

WebApi+sqlsugar+仓储模式_第4张图片

5.安装sqlsugar包

WebApi+sqlsugar+仓储模式_第5张图片

6.贴上代码

IRepository:

namespace IRepository
{
    public interface IBaseRepository<TEntity> where TEntity : class, new()
    {
        bool Create(TEntity entity);
        bool Delete(int id);
        bool Edit(TEntity entity);
        TEntity Find(int id);
        List<TEntity> QueryList();
    }
}

IProductRepository:

namespace IRepository
{
    public interface IProductRepository: IBaseRepository<Product>
    {
     //这里写IProductRepository的私有方法
    }
}

BaseRepository:

namespace Repository
{
    public class BaseRepository<TEntity> :SimpleClient<TEntity>, IBaseRepository<TEntity> where TEntity : class, new()
    {
        public BaseRepository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
        {
            base.Context = DbScoped.SugarScope;
            //创建库,创建表执行一次就可以注释
            //base.Context.DbMaintenance.CreateDatabase();
            //base.Context.CodeFirst.InitTables(
            //    typeof(Product)
            //    );
        }
        public bool Create(TEntity entity)
        {
            return base.Insert(entity);
        }
        public bool Delete(int id)
        {
            return base.DeleteById(id);
        }
        public bool Edit(TEntity entity)
        {
            return base.Update(entity);
        }
        public TEntity Find(int id)
        {
            return base.GetById(id);
        }
        public List<TEntity> QueryList()
        {
            return base.GetList();
        }
    }
}

ProductRepository:

namespace Repository
{
    public class ProductRepository: BaseRepository<Product>, IProductRepository
    {
        //这里写ProductRepository的私有方法
    }
}

IBaseService:

namespace IService
{
    public interface IBaseService<TEntity> where TEntity : class, new()
    {
        bool Create(TEntity entity);
        bool Delete(int id);
        bool Edit(TEntity entity);
        TEntity Find(int id);
        List<TEntity> QueryList();
    }
}

IProductService

namespace IService
{
    public interface IProductService: IBaseService<Product>
    {
    //这里写IProductService的私有方法
    }
}

BaseService:

namespace Service
{
    public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : class, new()
    {
        protected IBaseRepository<TEntity> _baseRepository;
        public bool Create(TEntity entity)
        {
            return _baseRepository.Create(entity);
        }

        public bool Delete(int id)
        {
            return _baseRepository.Delete(id);
        }

        public bool Edit(TEntity entity)
        {
            return _baseRepository.Edit(entity);
        }

        public TEntity Find(int id)
        {
            return _baseRepository.Find(id);
        }

        public List<TEntity> QueryList()
        {
            return _baseRepository.QueryList();
        }
    }
}

ProductService:

namespace Service
{
    public class ProductService: BaseService<Product>, IProductService
    {
        protected readonly IProductRepository  _productRepository;
        public ProductService(IProductRepository productRepository)
        {
            this._productRepository = productRepository;
            this._baseRepository = productRepository;
        }
    }
}

ProductController 控制器

namespace UniShop.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductService _productService;
        public ProductController(IProductService productService)
        {
            this._productService = productService;
        }
        [HttpGet("GetProduct")]
        public ActionResult<ApiResult> GetProduct()
        {
            var data = _productService.QueryList();
            if(data.Count==0) return ApiResultHelper.Error("请求失败");
            return ApiResultHelper.Success(data);
        }
    }
}

Startup.cs 注入 ORM:

namespace UniShop.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "UniShop.Api", Version = "v1" });
            });
            //注入 ORM
            services.AddSqlSugar(new IocConfig()
            {
                ConnectionString = this.Configuration.GetConnectionString("sqlConn"),
                DbType = IocDbType.SqlServer,
                IsAutoCloseConnection = true//自动释放
            });
            services.AddScoped<IProductRepository, ProductRepository>();
            services.AddScoped<IProductService, ProductService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "UniShop.Api v1"));
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

应该没啥了吧 SqlSugar ORM具体参考链接链接: SqlSugar ORM 官方文档

7.效果示例

WebApi+sqlsugar+仓储模式_第6张图片

你可能感兴趣的:(.net,c#,.net,core)