gpt4 book ai didi

c# - 使用 AutoMapper 如何在不使用 AfterMap 的情况下从映射的父级到子级集合成员获取值?

转载 作者:行者123 更新时间:2023-12-04 06:00:39 24 4
gpt4 key购买 nike

假设如下:

public class ParentSource
{
public Guid parentId { get; set; }

public ICollection<ChildSource> children { get; set; }
}

public class ChildSource
{
public Guid childId { get; set; }
}

public class ParentDestination
{
public Guid parentId { get; set; }

public ICollection<ChildDestination> children { get; set; }
}

public class ChildDestination
{
public Guid childId { get; set; }
public Guid parentId { get; set; }
public ParentDestination parent;
}

如何在不使用 .AfterMap 的情况下使用 AutoMapper 使用父级信息填充 ChildDestination 对象?

最佳答案

我认为在不使用 .AfterMap() 的情况下,使用对成员集合的父实例的引用来填充集合中的子对象的唯一方法带有定制TypeConverter<TSource, TDestination> .

class Program
{
static void Main(string[] args)
{
AutoMapper.Mapper.CreateMap<ParentSource, ParentDestination>().ConvertUsing<CustomTypeConverter>();

ParentSource ps = new ParentSource() { parentId = Guid.NewGuid() };
for (int i = 0; i < 3; i++)
{
ps.children.Add(new ChildSource() { childId = Guid.NewGuid() });
}

var mappedObject = AutoMapper.Mapper.Map<ParentDestination>(ps);

}
}

public class ParentSource
{
public ParentSource()
{
children = new HashSet<ChildSource>();
}

public Guid parentId { get; set; }
public ICollection<ChildSource> children { get; set; }
}

public class ChildSource
{
public Guid childId { get; set; }
}

public class ParentDestination
{
public ParentDestination()
{
children = new HashSet<ChildDestination>();
}
public Guid parentId { get; set; }
public ICollection<ChildDestination> children { get; set; }
}

public class ChildDestination
{
public Guid childId { get; set; }
public Guid parentId { get; set; }
public ParentDestination parent { get; set; }
}

public class CustomTypeConverter : AutoMapper.TypeConverter<ParentSource, ParentDestination>
{
protected override ParentDestination ConvertCore(ParentSource source)
{
var result = new ParentDestination() { parentId = source.parentId };
result.children = source.children.Select(c => new ChildDestination() { childId = c.childId, parentId = source.parentId, parent = result }).ToList();
return result;
}
}

或者你可以使用 .AfterMap() . :)

关于c# - 使用 AutoMapper 如何在不使用 AfterMap 的情况下从映射的父级到子级集合成员获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8948991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com