using AutoMapper;
using DMS.Core.Interfaces;
using DMS.Core.Models;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
namespace DMS.Application.Services;
///
/// 菜单应用服务,负责处理菜单相关的业务逻辑。
/// 实现 接口。
///
public class MenuService : IMenuService
{
private readonly IRepositoryManager _repoManager;
private readonly IMapper _mapper;
///
/// 构造函数,通过依赖注入获取仓储管理器和AutoMapper实例。
///
/// 仓储管理器实例。
/// AutoMapper 实例。
public MenuService(IRepositoryManager repoManager, IMapper mapper)
{
_repoManager = repoManager;
_mapper = mapper;
}
///
/// 异步根据ID获取菜单数据传输对象。
///
/// 菜单ID。
/// 菜单数据传输对象。
public async Task GetMenuByIdAsync(int id)
{
var menu = await _repoManager.Menus.GetByIdAsync(id);
return _mapper.Map(menu);
}
///
/// 异步获取所有菜单数据传输对象列表。
///
/// 菜单数据传输对象列表。
public async Task> GetAllMenusAsync()
{
var menus = await _repoManager.Menus.GetAllAsync();
return _mapper.Map>(menus);
}
///
/// 异步创建一个新菜单(事务性操作)。
///
/// 要创建的菜单数据传输对象。
/// 新创建菜单的ID。
/// 如果创建菜单时发生错误。
public async Task CreateMenuAsync(MenuBeanDto menuDto)
{
try
{
await _repoManager.BeginTranAsync();
var menu = _mapper.Map(menuDto);
await _repoManager.Menus.AddAsync(menu);
await _repoManager.CommitAsync();
return menu.Id;
}
catch (Exception ex)
{
await _repoManager.RollbackAsync();
throw new ApplicationException("创建菜单时发生错误,操作已回滚。", ex);
}
}
///
/// 异步更新一个已存在的菜单(事务性操作)。
///
/// 要更新的菜单数据传输对象。
/// 表示异步操作的任务。
/// 如果找不到菜单或更新菜单时发生错误。
public async Task UpdateMenuAsync(MenuBeanDto menuDto)
{
try
{
await _repoManager.BeginTranAsync();
var menu = await _repoManager.Menus.GetByIdAsync(menuDto.Id);
if (menu == null)
{
throw new ApplicationException($"Menu with ID {menuDto.Id} not found.");
}
_mapper.Map(menuDto, menu);
await _repoManager.Menus.UpdateAsync(menu);
await _repoManager.CommitAsync();
}
catch (Exception ex)
{
await _repoManager.RollbackAsync();
throw new ApplicationException("更新菜单时发生错误,操作已回滚。", ex);
}
}
///
/// 异步删除一个菜单(事务性操作)。
///
/// 要删除菜单的ID。
/// 表示异步操作的任务。
/// 如果删除菜单时发生错误。
public async Task DeleteMenuAsync(int id)
{
try
{
await _repoManager.BeginTranAsync();
await _repoManager.Menus.DeleteByIdAsync(id);
await _repoManager.CommitAsync();
}
catch (Exception ex)
{
await _repoManager.RollbackAsync();
throw new ApplicationException("删除菜单时发生错误,操作已回滚。", ex);
}
}
}