遵循以下步骤来搭建你的项目框架:
-
创建一个新的
.Net Core 7.0 WebApi
项目。 -
在 NuGet 包管理器控制台中添加
SqlSugar
包:Install-Package SqlSugar -Version 5.0.1
。 -
在项目中创建一个名为
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); }
-
在
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; } }
-
创建一个名为
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(); }
此实现中包含了一个用于处理所有事务和一些其他操作的单元。可在此处添加需要使用的所有仓储和获取它们的属性。此实现还在配置中处理了日志记录事件。
注意:必须提交所有响应改变的仓库,否则更改将回滚。
-
创建一个名为
IUnitOfWork.cs
的接口文件,并在其中包含以下代码:public interface IUnitOfWork : IDisposable { IRepository<Product> ProductRepository { get; } Task<bool> CommitAsync(); }
-
创建名为
Service
的文件夹,并在其中创建一个您需要的服务的文件(例如,IProductService.cs
、ProductService.cs
)。 -
在
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); }
-
在
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); } }
-
注册 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 项目框架的主要部分。您可以在需要使用的地方注入服务并使用其实现方法。