using Microsoft.EntityFrameworkCore; using UserPointManagement.Model; using UserPointManagement.Model.Dtos; using UserPointManagement.Model.Dtos.User; using UserPointManagement.Model.Entities; using UserPointManagement.Persistence; namespace UserPointManagement.Application.Services; public interface IUserService { Task> GetUsers(GetUserDto req); Task> GetAllUsers(); Task CreateUser(User input); Task DeleteUser(int userId); Task ModifyUser(int userId, ModifyUserDto input); } public class UserService : IUserService { private readonly IDbContextFactory _dbContextFactory; public UserService(IDbContextFactory dbContextFactory) { _dbContextFactory = dbContextFactory; } public async Task> GetUsers(GetUserDto req) { await using var _userPointManagementDbContext = await _dbContextFactory.CreateDbContextAsync(); var queryable = from user in _userPointManagementDbContext.Users select user; queryable = queryable.Where(x => x.Mobile.Contains(req.Keyword) || x.Name.Contains(req.Keyword), !string.IsNullOrEmpty(req.Keyword)); var count = queryable.Count(); var data = await queryable.OrderByDescending(x => x.Id).Paging(req).ToListAsync().ConfigureAwait(false); return new PageResultDto() { Items = data, TotalCount = count }; } public async Task> GetAllUsers() { await using var _userPointManagementDbContext = await _dbContextFactory.CreateDbContextAsync(); var users = await (from user in _userPointManagementDbContext.Users select new UserDto() { Id = user.Id, Name = user.Name }).ToListAsync().ConfigureAwait(false); return users; } public async Task CreateUser(User input) { await using var _userPointManagementDbContext = await _dbContextFactory.CreateDbContextAsync(); if (!string.IsNullOrWhiteSpace(input.Mobile) && _userPointManagementDbContext.Users.Any(x => x.Mobile == input.Mobile)) { throw new ArgumentException("手机号不可重复!"); } if (_userPointManagementDbContext.Users.Any(x => x.Name == input.Name)) { throw new ArgumentException("名称不可重复!"); } _userPointManagementDbContext.Users.Add(input); await _userPointManagementDbContext.SaveChangesAsync().ConfigureAwait(false); } public async Task DeleteUser(int userId) { await using var _userPointManagementDbContext = await _dbContextFactory.CreateDbContextAsync(); var user = await _userPointManagementDbContext.Users.FirstOrDefaultAsync(x => x.Id == userId) .ConfigureAwait(false); _userPointManagementDbContext.Users.Remove(user); await _userPointManagementDbContext.SaveChangesAsync().ConfigureAwait(false); } public async Task ModifyUser(int userId, ModifyUserDto input) { await using var _userPointManagementDbContext = await _dbContextFactory.CreateDbContextAsync(); var user = await _userPointManagementDbContext.Users.FirstOrDefaultAsync(x => x.Id == userId) .ConfigureAwait(false); user.Mobile = input.Mobile; user.Name = input.Name; _userPointManagementDbContext.Users.Update(user); await _userPointManagementDbContext.SaveChangesAsync().ConfigureAwait(false); } }