91 lines
2.6 KiB
C#
91 lines
2.6 KiB
C#
using Model;
|
||
using Model.Entity;
|
||
using ORM;
|
||
using Service.Implement;
|
||
|
||
public class UserService: BaseService<UserEntity>
|
||
{
|
||
public UserService(SqlSugarRepository<UserEntity> repository) : base(repository)
|
||
{
|
||
}
|
||
|
||
public async Task<Result<UserEntity>> GetUserByUserNameAsync(string username)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(username))
|
||
return Result<UserEntity>.Error("用户名不能为空");
|
||
|
||
try
|
||
{
|
||
var user = await _repository.Entities
|
||
.Where(x => x.UserName == username)
|
||
.FirstAsync();
|
||
|
||
if (user == null)
|
||
return Result<UserEntity>.Error("用户不存在");
|
||
|
||
return Result<UserEntity>.Success(user);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return Result<UserEntity>.Error("获取用户失败", ex);
|
||
}
|
||
}
|
||
|
||
public override async Task<Result<bool>> InsertAsync(UserEntity entity)
|
||
{
|
||
if (entity == null)
|
||
return Result<bool>.Error("用户数据不能为空");
|
||
|
||
try
|
||
{
|
||
// 唯一性校验
|
||
bool exists = await _repository.Entities
|
||
.AnyAsync(x => x.UserName == entity.UserName);
|
||
|
||
if (exists)
|
||
return Result<bool>.Error("用户名已存在");
|
||
|
||
var result = await _repository.InsertAsync(entity);
|
||
|
||
return Result<bool>.Success(result);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return Result<bool>.Error("插入数据失败", ex);
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 更新单条用户记录
|
||
/// </summary>
|
||
/// <param name="entity">要更新的用户实体,Id 必须有值</param>
|
||
public async Task<Result<bool>> UpdateAsync(UserEntity entity)
|
||
{
|
||
if (entity == null)
|
||
return Result<bool>.Error("用户数据不能为空");
|
||
|
||
if (entity.Id <= 0)
|
||
return Result<bool>.Error("主键 Id 无效,无法更新");
|
||
|
||
try
|
||
{
|
||
// 唯一性校验(可选,如果允许改用户名就检查)
|
||
bool exists = await _repository.Entities
|
||
.Where(x => x.UserName == entity.UserName && x.Id != entity.Id)
|
||
.AnyAsync();
|
||
|
||
if (exists)
|
||
return Result<bool>.Error("用户名已存在");
|
||
|
||
// 更新整个实体
|
||
var result = await _repository.UpdateAsync(entity);
|
||
|
||
return Result<bool>.Success(result);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return Result<bool>.Error("更新用户失败", ex);
|
||
}
|
||
}
|
||
|
||
}
|