using System.Diagnostics;
using AutoMapper;
using DMS.Core.Interfaces.Repositories;
using DMS.Core.Models;
using DMS.Infrastructure.Data;
using DMS.Infrastructure.Entities;
using Microsoft.Extensions.Logging;
namespace DMS.Infrastructure.Repositories;
///
/// 设备仓储实现类,负责设备数据的持久化操作。
/// 继承自 并实现 接口。
///
public class DeviceRepository : BaseRepository, IDeviceRepository
{
private readonly IMapper _mapper;
///
/// 构造函数,注入 AutoMapper 和 SqlSugarDbContext。
///
/// AutoMapper 实例,用于实体模型和数据库模型之间的映射。
/// SqlSugar 数据库上下文,用于数据库操作。
/// 日志记录器实例。
public DeviceRepository(IMapper mapper, SqlSugarDbContext dbContext, ILogger logger)
: base(dbContext, logger)
{
_mapper = mapper;
}
///
/// 异步获取所有设备。
///
/// 包含所有设备实体的列表。
public async Task> GetAllAsync()
{
var dbList = await base.GetAllAsync();
return _mapper.Map>(dbList);
}
///
/// 异步根据ID获取单个设备。
///
/// 设备的唯一标识符。
/// 对应的设备实体,如果不存在则为null。
public async Task GetByIdAsync(int id)
{
var dbDevice = await base.GetByIdAsync(id);
return _mapper.Map(dbDevice);
}
///
/// 异步添加新设备。
///
/// 要添加的设备实体。
/// 添加成功后的设备实体(包含数据库生成的ID等信息)。
public async Task AddAsync(Core.Models.Device model)
{
var dbDevice = await base.AddAsync(_mapper.Map(model));
return _mapper.Map(dbDevice, model);
}
///
/// 异步更新现有设备。
///
/// 要更新的设备实体。
/// 受影响的行数。
public async Task UpdateAsync(Core.Models.Device model) => await base.UpdateAsync(_mapper.Map(model));
///
/// 异步删除设备。
///
/// 要删除的设备实体。
/// 受影响的行数。
public async Task DeleteAsync(Core.Models.Device model) => await base.DeleteAsync(_mapper.Map(model));
///
/// 异步根据ID删除设备。
///
/// 要删除设备的唯一标识符。
/// 受影响的行数。
public async Task DeleteByIdAsync(int id)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = await _dbContext.GetInstance().Deleteable(new DbDevice() { Id = id })
.ExecuteCommandAsync();
stopwatch.Stop();
_logger.LogInformation($"Delete {typeof(DbDevice)},ID={id},耗时:{stopwatch.ElapsedMilliseconds}ms");
return result;
}
///
/// 异步获取指定数量的设备。
///
/// 要获取的设备数量。
/// 包含指定数量设备实体的列表。
public new async Task> TakeAsync(int number)
{
var dbList = await base.TakeAsync(number);
return _mapper.Map>(dbList);
}
public async Task> AddBatchAsync(List entities)
{
var dbEntities = _mapper.Map>(entities);
var addedEntities = await base.AddBatchAsync(dbEntities);
return _mapper.Map>(addedEntities);
}
}