自动地图对象

本文关键字:对象 地图 | 更新日期: 2023-09-27 18:15:23

我有一个奇怪的情况,我有object s的object s和List s作为我的实体和合同的一部分,与第三方服务接口。我要试着看看我是否可以用实体和契约中更具体的东西代替实际的对象类来解决这个问题,但我很好奇是否有一种方法可以让AutoMapper按此处理。

下面是一些虚拟类:

public class From
{
    public object Item { get; set; }
}
public class FromObject
{
    public string Value { get; set; }
}
public class To
{
    public object Item { get; set; }
}
public class ToObject
{
    public string Value { get; set; }
}

和快速复制:

Mapper.CreateMap<From, To>();
Mapper.CreateMap<FromObject, ToObject>();
From from = new From { Item = new FromObject { Value = "Test" } };
To to = Mapper.Map<To>(from);
string type = to.Item.GetType().Name; // FromObject

基本上,问题是这样的:是否有一种方法可以让AutoMapper理解from.ItemFromObject并将映射应用到ToObject ?我想可能没有办法使其自动,因为没有什么可以表明to.Item必须是ToObject,但是在CreateMapMap调用期间是否有办法指定应该考虑到这一点?

自动地图对象

我不认为有一个"自动"的方式做这件事,因为AutoMapper将无法计算出From.ItemFromObjectTo.ItemToObject

但是,在创建映射时,您可以指定

Mapper.CreateMap<FromObject, ToObject>();
Mapper.CreateMap<From, To>()
    .ForMember(dest => dest.Item, opt => opt.MapFrom(src => Mapper.Map<ToObject>(src.Item)));            
From from = new From { Item = new FromObject { Value = "Test" } };
To to = Mapper.Map<To>(from);
string type = to.Item.GetType().Name; // ToObject

如果您愿意使用额外的接口,可以使用Include来完成。但是,您不能以这种方式将object映射到object

public class From
{
    public IItem Item { get; set; }
}
public class FromObject : IItem
{
    public string Value { get; set; }
}
public class To
{
    public object Item { get; set; }
}
public class ToObject
{
    public string Value { get; set; }
}
public interface IItem
{
    // Nothing; just for grouping.
}
Mapper.CreateMap<From, To>();
Mapper.CreateMap<IItem, object>()
    .Include<FromObject, ToObject>();
From from = new From { Item = new FromObject { Value = "Test" } };
To to = Mapper.Map<To>(from);
string type = to.Item.GetType().Name; // ToObject