遵循以下步骤来搭建你的项目框架:
创建一个新的 .Net Core 7.0 WebApi
项目。
在 NuGet 包管理器控制台中添加 SqlSugar
包: Install-Package SqlSugar -Version 5.0.1
。
在项目中创建一个名为 Repository
的文件夹,并在其中创建一个名为 IRepository.cs
的接口文件,该接口应包含以下代码:
public interface IRepository where T : class, new()
{
Task GetSingle(Expression> whereExpression);
Task> GetList(Expression> whereExpression);
Task> GetPageList(Expression> whereExpression, PageModel page);
Task Add(T entity);
Task Update(T entity);
Task Delete(T entity);
}
在 Repository
文件夹中创建另一个名为 BaseRepository.cs
的实现 IRepository
接口的类文件,并包含以下代码:
public class BaseRepository : IRepository where T : class, new()
{
private readonly ISqlSugarClient _db;
public BaseRepository(ISqlSugarClient db)
{
_db = db;
}
public async Task GetSingle(Expression> whereExpression)
{
return await Task.Run(() => _db.Queryable().First(whereExpression));
}
public async Task> GetList(Expression> whereExpression)
{
return await Task.Run(() => _db.Queryable().Where(whereExpression).ToList());
}
public async Task> GetPageList(Expression> whereExpression, PageModel page)
{
return await Task.Run(() =>
_db.Queryable()
.Where(whereExpression)
.OrderBy(page.OrderBy)
.ToPageList(page.PageIndex, page.PageSize));
}
public async Task Add(T entity)
{
return await _db.Insertable(entity).ExecuteCommandAsync();
}
public async Task Update(T entity)
{
return await _db.Updateable(entity).ExecuteCommandAsync() > 0;
}
public async Task 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 _productRepository;
public IRepository ProductRepository
{
get
{
if (_productRepository == null)
{
_productRepository = new BaseRepository(_db);
}
return _productRepository;
}
}
public async Task 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 ProductRepository { get; }
Task CommitAsync();
}
创建名为 Service
的文件夹,并在其中创建一个您需要的服务的文件(例如,IProductService.cs
、ProductService.cs
)。
在 IProductService.cs
文件中,定义您的服务接口,如下所示:
public interface IProductService
{
Task GetSingle(int id);
Task> GetAll();
Task Create(Product product);
Task Update(Product product);
Task Delete(int id);
}
在 ProductService.cs
文件中,定义您的服务实现类,并实现 IProductService
接口。我们将使用上述的仓储实现,如下所示:
public class ProductService : IProductService
{
private readonly IUnitOfWork _unitOfWork;
public ProductService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task GetSingle(int id)
{
return await _unitOfWork.ProductRepository.GetSingle(p => p.Id == id);
}
public async Task> GetAll()
{
return await _unitOfWork.ProductRepository.GetList(p => true);
}
public async Task Create(Product product)
{
product.CreatedDate = DateTime.Now;
product.UpdatedDate = DateTime.Now;
return await _unitOfWork.ProductRepository.Add(product);
}
public async Task 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 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(provider => new SqlSugarClient(
new ConnectionConfig
{
// 数据库连接字符串
ConnectionString = Configuration.GetConnectionString("DefaultConnection"),
// 配置其他选项...
}));
// 注册仓储服务和服务接口实现
services.AddScoped();
services.AddScoped();
以上就是 SqlSugar+异步泛型仓储
实现 WebApi 项目框架的主要部分。您可以在需要使用的地方注入服务并使用其实现方法。