
Windows
- 1 ответ
- 0 вопросов
0
Вклад в тег
CreateMap<ExportRetail, ExportRetailDto>()
.ForMember(dest => dest.ExportRetailNomenklatura, opt => opt.MapFrom((src, dest, _, ctx) =>
ExpandHelper.MapWithDepthControl(src, ctx, (source, depth) =>
src.ExportRetailNomenklaturaId == null ? null : ExpandHelper.HasExpand(ctx, "nomenklatura", depth)
? ctx.Mapper.Map<NomenklaturaDto>(src.ExportRetailNomenklatura)
: new NomenklaturaDto { InternalId = src.ExportRetailNomenklaturaId.Value })))
public enum ExpandMatchMode
{
Exact,
StartsWith,
EndsWith,
Contains
}
public static class ExpandHelper
{
public static bool HasExpand(ResolutionContext ctx, string pattern, int depth = 0)
{
return ctx.Items.TryGetValue("expand", out var obj) &&
obj is string[] expandArray &&
expandArray.Any(expandItem =>
{
var segments = expandItem.Split('.');
return depth >= 0 &&
depth < segments.Length &&
segments[depth].Equals(pattern, StringComparison.OrdinalIgnoreCase);
});
}
public static TResult MapWithDepthControl<TSource, TResult>(
TSource source,
ResolutionContext ctx,
Func<TSource, int, TResult> mappingFunc)
{
int currentDepth = GetOrInitializeDepth(ctx);
// Увеличиваем глубину для вложенных вызовов
ctx.Items["TypeDepth"] = currentDepth + 1;
try
{
return mappingFunc(source, currentDepth);
}
finally
{
// Восстанавливаем оригинальную глубину
ctx.Items["TypeDepth"] = currentDepth;
}
}
private static int GetOrInitializeDepth(ResolutionContext ctx)
{
if (!ctx.Items.TryGetValue("TypeDepth", out var depthObj))
{
depthObj = 0;
ctx.Items["TypeDepth"] = depthObj;
}
return (int)depthObj;
}
}
}