.Net Core7.0 WebApi 项目框架搭建 : Sqlsugar+异步泛型仓储

遵循以下步骤来搭建你的项目框架:

  1. 创建一个新的 .Net Core 7.0 WebApi 项目。

  2. 在 NuGet 包管理器控制台中添加 SqlSugar 包: Install-Package SqlSugar -Version 5.0.1

  3. 在项目中创建一个名为 Repository 的文件夹,并在其中创建一个名为 IRepository.cs 的接口文件,该接口应包含以下代码:

    public interface IRepository<T> where T : class, new()
     {
         Task<T> GetSingle(Expression<Func<T, bool>> whereExpression);
         Task<List<T>> GetList(Expression<Func<T, bool>> whereExpression);
         Task<List<T>> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel page);
         Task<int> Add(T entity);
         Task<bool> Update(T entity);
         Task<bool> Delete(T entity);
     }
    
  4. Repository 文件夹中创建另一个名为 BaseRepository.cs 的实现 IRepository<T> 接口的类文件,并包含以下代码:

    public class BaseRepository<T> : IRepository<T> where T : class, new()
     {
         private readonly ISqlSugarClient _db;
    
         public BaseRepository(ISqlSugarClient db)
         {
             _db = db;
         }
    
         public async Task<T> GetSingle(Expression<Func<T, bool>> whereExpression)
         {
             return await Task.Run(() => _db.Queryable<T>().First(whereExpression));
         }
    
         public async Task<List<T>> GetList(Expression<Func<T, bool>> whereExpression)
         {
             return await Task.Run(() => _db.Queryable<T>().Where(whereExpression).ToList());
         }
    
         public async Task<List<T>> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel page)
         {
             return await Task.Run(() =>
                                                    _db.Queryable<T>()
                                                    .Where(whereExpression)
                                                    .OrderBy(page.OrderBy)
                                                    .ToPageList(page.PageIndex, page.PageSize));
         }
    
         public async Task<int> Add(T entity)
         {
             return await _db.Insertable(entity).ExecuteCommandAsync();
         }
    
         public async Task<bool> Update(T entity)
         {
             return await _db.Updateable(entity).ExecuteCommandAsync() > 0;
         }
    
         public async Task<bool> Delete(T entity)
         {
             return await _db.Deleteable(entity).ExecuteCommandAsync() > 0;
         }
     }
    
  5. 创建一个名为 UnitOfWork.cs 的文件,并包含以下代码:

    public class UnitOfWork : IUnitOfWork
     {
         private readonly ISqlSugarClient _db;
    
         public UnitOfWork(IConfiguration configuration, ILoggerFactory loggerFactory)
         {
             var connectionString = configuration.GetConnectionString("DefaultConnection");
    
             _db = new SqlSugarClient(new ConnectionConfig
             {
                 ConnectionString = connectionString,
                 // DbType = DbType.SqlServer, // optional
                 // InitKeyType = InitKeyType.Attribute, // optional
                 // IsAutoCloseConnection = false, // default false
                 // IsShardSameThread = true, // optional
                 // ConfigureExternalServices = new ConfigureExternalServices
                 // {
                 //     DataInfoCacheService = new HttpRuntimeCache() // optional
                 // },
                 AopEvents = new AopEvents
                 {
                     OnLogExecuted = (sql, pars) =>
                     {
                         loggerFactory.CreateLogger("SqlSugar").LogInformation("SqlSugar: " + sql + "\r\n" + JsonConvert.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                     }
                 }
             });
         }
    
         private IRepository<Product> _productRepository;
    
         public IRepository<Product> ProductRepository
         {
             get
             {
                 if (_productRepository == null)
                 {
                     _productRepository = new BaseRepository<Product>(_db);
                 }
                 return _productRepository;
             }
         }
    
         public async Task<bool> CommitAsync()
         {
             return await _db.Ado.UseTranAsync(async () =>
             {
                 var commit = true;
    
                 // TODO: Add all repositories that need to be committed here.
                 if (_productRepository != null)
                 {
                     commit = commit && await _productRepository.CommitAsync();
                 }
    
                 return commit;
             });
         }
    
         public void Dispose()
         {
             _db.Dispose();
             GC.SuppressFinalize(this);
         }
    
         // TODO: Add all repositories that need to be disposed in here.
         //       Example: _productRepository?.Dispose();
    
     }
    

    此实现中包含了一个用于处理所有事务和一些其他操作的单元。可在此处添加需要使用的所有仓储和获取它们的属性。此实现还在配置中处理了日志记录事件。

    注意:必须提交所有响应改变的仓库,否则更改将回滚。

  6. 创建一个名为 IUnitOfWork.cs 的接口文件,并在其中包含以下代码:

    public interface IUnitOfWork : IDisposable
     {
         IRepository<Product> ProductRepository { get; }
    
         Task<bool> CommitAsync();
     }
    
  7. 创建名为 Service 的文件夹,并在其中创建一个您需要的服务的文件(例如,IProductService.csProductService.cs)。

  8. IProductService.cs 文件中,定义您的服务接口,如下所示:

    public interface IProductService
     {
         Task<Product> GetSingle(int id);
         Task<List<Product>> GetAll();
         Task<int> Create(Product product);
         Task<bool> Update(Product product);
         Task<bool> Delete(int id);
     }
    
  9. ProductService.cs 文件中,定义您的服务实现类,并实现 IProductService 接口。我们将使用上述的仓储实现,如下所示:

    public class ProductService : IProductService
     {
         private readonly IUnitOfWork _unitOfWork;
    
         public ProductService(IUnitOfWork unitOfWork)
         {
             _unitOfWork = unitOfWork;
         }
    
         public async Task<Product> GetSingle(int id)
         {
             return await _unitOfWork.ProductRepository.GetSingle(p => p.Id == id);
         }
    
         public async Task<List<Product>> GetAll()
         {
             return await _unitOfWork.ProductRepository.GetList(p => true);
         }
    
         public async Task<int> Create(Product product)
         {
             product.CreatedDate = DateTime.Now;
             product.UpdatedDate = DateTime.Now;
    
             return await _unitOfWork.ProductRepository.Add(product);
         }
    
         public async Task<bool> Update(Product product)
         {
             var existingProduct = await _unitOfWork.ProductRepository.GetSingle(p => p.Id == product.Id);
             if (existingProduct == null)
             {
                 return false;
             }
    
             existingProduct.Name = product.Name;
             existingProduct.Price = product.Price;
             existingProduct.UpdatedDate = DateTime.Now;
    
             return await _unitOfWork.ProductRepository.Update(existingProduct);
         }
    
         public async Task<bool> Delete(int id)
         {
             var existingProduct = await _unitOfWork.ProductRepository.GetSingle(p => p.Id == id);
             if (existingProduct == null)
             {
                 return false;
             }
    
             return await _unitOfWork.ProductRepository.Delete(existingProduct);
         }
     }
    
  10. 注册 SqlSugar 客户端和仓储服务。打开 Startup.cs 文件,添加以下代码:

// 注册 SqlSugar 客户端
services.AddScoped<ISqlSugarClient>(provider => new SqlSugarClient(
   new ConnectionConfig
   {
       // 数据库连接字符串
       ConnectionString = Configuration.GetConnectionString("DefaultConnection"),

       // 配置其他选项...   
  }));

// 注册仓储服务和服务接口实现
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IProductService, ProductService>();

以上就是 SqlSugar+异步泛型仓储 实现 WebApi 项目框架的主要部分。您可以在需要使用的地方注入服务并使用其实现方法。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Vue 3 + TypeScript 中,是一个非常常用的技巧,可以帮助我们编写出更加通用、可复用的代码。下面是一个的高级运用实例: 假设我们有一个表单组件,它的数据模是一个对象,其中每个属性都有一个对应的输入框,我们可以编写一个 `Form` 组件来实现这个表单。为了让 `Form` 组件更加通用,我们可以使用来实现: ```typescript // 定义表单数据模的类 interface FormModel { [key: string]: any } // 定义表单项的类 interface FormItem<T> { label: string prop: keyof T } // 定义表单组件的 props 类 interface FormProps<T extends FormModel> { model: T items: Array<FormItem<T>> } // 定义表单组件 export default defineComponent<FormProps<FormModel>>({ name: 'Form', props: { model: Object as PropType<FormModel>, items: Array as PropType<Array<FormItem<FormModel>>> }, setup(props) { const handleSubmit = () => { // 处理表单提交逻辑 } return { handleSubmit } } }) ``` 在上面的代码中,我们定义了一个 `Form` 组件,它接收两个 props:`model` 和 `items`,其中 `model` 是一个,它可以是任意一个类似于表单数据模的对象,`items` 是一个数组,其中每个元素都是一个 `FormItem` 类的对象,表示一个表单项。在组件中,我们使用 `keyof` 关键字来获取 `T` 的所有属性名,然后使用 `Array<FormItem<T>>` 来表示 `items` 的类,这样就可以在使用组件时传入任意一个数据模和表单项,从而实现组件的通用性和灵活性。 以上是一个 Vue 3 + TypeScript 中的高级运用实例,通过使用,我们可以编写出更加通用、可复用的组件和方法,从而提高代码的复用性和灵活性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值