Files
tnb.server/EquipMgr/Tnb.EquipMgr/BaseMoldMaintainService.cs
2023-05-18 18:15:38 +08:00

89 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using JNPF.Common.Enums;
using JNPF.Common.Security;
using JNPF.FriendlyException;
using SqlSugar;
using Tnb.EquipMgr.Entities.Dto;
using Tnb.EquipMgr.Entities;
using Tnb.EquipMgr.Utils;
using Mapster;
using JNPF.Common.Contracts;
namespace Tnb.EquipMgr
{
public class BaseMoldMaintainService
{
private readonly ISqlSugarClient _db;
public BaseMoldMaintainService(ISqlSugarClient db)
{
_db = db;
}
/// <summary>
/// 关联
/// </summary>
/// <typeparam name="TSrc">输入参数类型</typeparam>
/// <typeparam name="TDest">目标数据库表类型</typeparam>
/// <param name="input">输入参数</param>
/// <param name="mColumnName">主表属性名称</param>
/// <param name="name">次表属性名称</param>
/// <param name="deleleExp">删除条件</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
protected async Task Relevance<TSrc, TDest>(TSrc input, string mColumnName, string name, Expression<Func<TDest, bool>> deleleExp) where TDest : BaseEntity<string>, new()
where TSrc : BaseMoldMaintainInput
{
await _db.Deleteable<TDest>().Where(deleleExp).ExecuteCommandAsync();
if (input == null) throw new ArgumentNullException(nameof(input));
var entities = new List<TDest>();
if (input.ids?.Count > 0)
{
foreach (var id in input.ids)
{
var pk = id;
TDest entity = new();
entity.id = SnowflakeIdHelper.NextId();
if (!PropertySet<TDest>.ValueFactories.TryGetValue(mColumnName, out Action<object, object>? setGroupIdAction))
{
setGroupIdAction = PropertySet<TDest>.CreateSetPropertyValueAction(mColumnName);
PropertySet<TDest>.ValueFactories.Add(mColumnName, setGroupIdAction);
}
setGroupIdAction(entity, input.item_group_id);
if (!PropertySet<TDest>.ValueFactories.TryGetValue(name, out Action<object, object>? setAction))
{
setAction = PropertySet<TDest>.CreateSetPropertyValueAction(name);
PropertySet<TDest>.ValueFactories.Add(name, setAction);
}
setAction(entity, pk);
entities.Add(entity);
}
}
var row = await _db.Insertable(entities).ExecuteCommandAsync();
if (row < 1) throw Oops.Oh(ErrorCode.COM1000);
}
protected async Task<dynamic> GetListByMasterId<TRelaction, TDest, TOutput>(string masterId,
Expression<Func<TRelaction, bool>> masterFilterExp,
Expression<Func<TRelaction, string>> masterSelector,
Expression<Func<TDest, bool>> relactionFilterExp)
{
var config = new TypeAdapterConfig();
config.ForType<TDest, TOutput>();
var list = new List<TOutput>();
var itemIds = await _db.Queryable<TRelaction>().Where(masterFilterExp).Select(masterSelector).ToListAsync();
if (itemIds?.Count > 0)
{
var items = await _db.Queryable<TDest>().Where(relactionFilterExp).ToListAsync();
list = items.Adapt<List<TOutput>>();
}
return list;
}
}
}