假设如下:
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;
}
如何使用 AutoMapper 在不使用 .AfterMap
的情况下使用父级信息填充 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/