1、通过github地址:https://github.com/arch/UnitOfWork,下载UnitOfWork的代码,将工作单元部分的代码引用到自己的项目,新增UnitOfWork文件夹。
2、在UnitOfWork文件夹下引用UnitOfWork下的IPagedList.cs、PagedList.cs类,WPFProjectAPI项目引用WPFProjectShared项目。
3、然后在program.cs下添加UnitOfWork的服务:
//添加数据库上下文服务
builder.Services.AddDbContext<MyDbContext>(options =>
{string DbConnectionstring = builder.Configuration.GetConnectionString("DbConnectionString");options.UseSqlServer(DbConnectionstring);
}).AddUnitOfWork<MyDbContext>();
4、新建控制器UserController测试下工作单元的使用 ,先新建基础控制器BaseApiController,全局Resful风格代码(详见.Net Core6.0 WebAPI项目框架搭建二:实现Resful风格_痕迹0302的博客-CSDN博客):
[Route("api/[controller]/[action]")][ApiController]public class BaseApiController : ControllerBase{}
5、UserController 继承BaseApiController,依赖注入IUnitOfWork,新增查询人员、删除人员、添加人员的测试代码:
public class UserController : BaseApiController{private readonly IUnitOfWork unitOfWork;public UserController(IUnitOfWork unitOfWork){this.unitOfWork = unitOfWork;}/// <summary>/// 获取人员信息/// </summary>/// <returns></returns>[HttpGet]public async Task<IEnumerable<User>> GetUserList(){var res = unitOfWork.GetRepository<User>();var list = await res.GetAllAsync();return list;}/// <summary>/// 添加人员/// </summary>/// <param name="user"></param>/// <returns></returns>[HttpPost]public async Task<IActionResult> AddUser(User user){var r = await unitOfWork.GetRepository<User>().InsertAsync(user);var result = await unitOfWork.SaveChangesAsync();if (result > 0){return Ok("添加人员成功!");}else{return BadRequest("添加人员失败!");}}/// <summary>/// 删除人员/// </summary>/// <param name="Id"></param>/// <returns></returns>[HttpDelete]public async Task<IActionResult> DeleteUser(int Id){var user = await unitOfWork.GetRepository<User>().FindAsync(Id);if(user == null){return NotFound("没有找到待删除的人员!");}else{unitOfWork.GetRepository<User>().Delete(user);if(await unitOfWork.SaveChangesAsync() > 0){return Ok($"删除账号:{user.Account}成功!");}else{return BadRequest("删除数据失败!");}}}}
6、F5运行项目: