WebApi+sqlsugar+仓储模式

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

1.创建模板

在这里插入图片描述

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

在这里插入图片描述

3.打钩OpenAPI会自动配置swagger

在这里插入图片描述
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层,添加类库

在这里插入图片描述

5.安装sqlsugar包

在这里插入图片描述

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.效果示例

在这里插入图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
仓储模式是一种常见的设计模式,用于将数据访问逻辑与业务逻辑分离。在 C# 中,可以使用 SqlSugar 实现仓储模式。 首先,需要定义一个接口,用于声明对数据访问的操作: ```csharp public interface IRepository<T> { IEnumerable<T> GetAll(); T GetById(int id); void Add(T entity); void Update(T entity); void Delete(int id); } ``` 然后,实现这个接口: ```csharp public class Repository<T> : IRepository<T> where T : class, new() { private readonly SqlSugarClient _db; public Repository(SqlSugarClient db) { _db = db; } public IEnumerable<T> GetAll() { return _db.Queryable<T>().ToList(); } public T GetById(int id) { return _db.Queryable<T>().InSingle(id); } public void Add(T entity) { _db.Insertable(entity).ExecuteCommand(); } public void Update(T entity) { _db.Updateable(entity).ExecuteCommand(); } public void Delete(int id) { _db.Deleteable<T>().In(id).ExecuteCommand(); } } ``` 在这个实现中,使用了 SqlSugar 提供的 Queryable、Insertable、Updateable 和 Deleteable 方法来执行对数据库的操作。 最后,可以在业务逻辑中使用这个仓储来访问数据: ```csharp public class UserService { private readonly IRepository<User> _userRepository; public UserService(IRepository<User> userRepository) { _userRepository = userRepository; } public IEnumerable<User> GetAllUsers() { return _userRepository.GetAll(); } public User GetUserById(int id) { return _userRepository.GetById(id); } public void AddUser(User user) { _userRepository.Add(user); } public void UpdateUser(User user) { _userRepository.Update(user); } public void DeleteUser(int id) { _userRepository.Delete(id); } } ``` 这样,就可以将数据访问逻辑和业务逻辑分离,使代码更加清晰和易于维护。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值