BOB/Service/Implement/BaseService.cs
2025-12-04 10:51:21 +08:00

93 lines
3.1 KiB
C#

using Model;
using Model.SQLModel;
using ORM;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Service.Implement
{
public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : BaseEntity, new()
{
protected readonly SqlSugarRepository<TEntity> _repository;
public BaseService(SqlSugarRepository<TEntity> repository)
{
_repository = repository;
}
/// <summary>
/// 查询全部
/// </summary>
public async Task<Result<List<TEntity>>> GetAllAsync()
{
try
{
var list = await _repository.Entities.ToListAsync();
return Result<List<TEntity>>.Success(list);
}
catch (Exception ex)
{
return Result<List<TEntity>>.Error("查询所有数据失败", ex);
}
}
/// <summary>
/// 分页查询
/// </summary>
public async Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total)
{
try
{
var list = await _repository.Entities
.OrderBy(d => d.Id)
.ToPageListAsync(pageIndex, pageSize, total);
total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
return Result<List<TEntity>>.Success(list);
}
catch (Exception ex)
{
return Result<List<TEntity>>.Error("分页查询数据失败", ex);
}
}
/// <summary>
/// 分页查询,并可以根据日期范围进行过滤
/// </summary>
public async Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total, DateTime? startDate, DateTime? endDate)
{
try
{
var list = await _repository.Entities
.Where(x=>x.CollectTime>=startDate&&x.CollectTime<=endDate)
.OrderBy(d => d.Id)
.ToPageListAsync(pageIndex, pageSize, total);
total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
return Result<List<TEntity>>.Success(list);
}
catch (Exception ex)
{
return Result<List<TEntity>>.Error("分页查询数据失败", ex);
}
}
/// <summary>
/// 插入单条数据
/// </summary>
public async Task<Result<bool>> InsertAsync(TEntity entity)
{
try
{
var result = await _repository.Context.Insertable(entity).ExecuteCommandAsync();
return Result<bool>.Success(result > 0);
}
catch (Exception ex)
{
return Result<bool>.Error("插入数据失败", ex);
}
}
}
}