ASP.NET Core模块化前后端分离快速开发框架介绍之3、数据访问模块介绍 (2)

是否存在

_repository.ExistsAsync(m => m.Title.Contains("test")) 批量修改 /// <summary> /// 批量修改状态 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> public Task<bool> UpdateStatus(List<Guid> ids, ProductStatus status) { return Db.Find(m => ids.Contains(m.Id)).UpdateAsync(m => new ProductEntity { Status = status }); } 批量删除 /// <summary> /// 批量删除 /// </summary> /// <param></param> /// <returns></returns> public Task<bool> Delete(string title) { return Db.Find(m => m.Title.Contains(title)).DeleteAsync(); } 表连接查询 public async Task<IList<ProductEntity>> Query(ProductQueryModel model) { //分页 var paging = model.Paging(); var query = Db.Find(); query.WhereIf(model.Title.NotNull(), m => m.Title.Contains(model.Title)); //设置默认排序 if (!paging.OrderBy.Any()) { query.OrderByDescending(m => m.Id); } var list = await query.LeftJoin<AccountEntity>((x, y) => x.CreatedBy == y.Id) .Select((x, y) => new { x, Creator = y.Name }) .PaginationAsync(paging); model.TotalCount = paging.TotalCount; return list; } 分组查询 Db.Find().GroupBy(m => new { m.Status }).Select(m => new { m.Key.Status, Count = m.Count() }); 工作单元

工作单元在服务中注入使用

private readonly IUnitOfWork _uow; public ArticleService(IUnitOfWork<MalDbContext> uow) { _uow = uow; }

然后通过BeginTransaction方法开启事务,Commit方法提交事务,Rollback方法回滚事务

_uow.BeginTransaction(); var result = await _accountRepository.AddAsync(account); if (result) { if (model.Roles != null && model.Roles.Any()) { var accountRoleList = model.Roles.Select(m => new AccountRoleEntity { AccountId = account.Id, RoleId = m }).ToList(); if (await _accountRoleRepository.AddAsync(accountRoleList)) { _uow.Commit(); return ResultModel.Success(); } } else { _uow.Commit(); return ResultModel.Success(); } }

好了,数据库访问的用法大致就是这样~

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyddyp.html