使用 AutoMapper 覆盖解析的 属性 类型
Override resolved property type with AutoMapper
使用 AutoMapper,我可以覆盖 属性 的解析类型吗?例如,给定这些 类:
public class Parent
{
public Child Value { get; set; }
}
public class Child { ... }
public class DerivedChild : Child { ... }
我可以将 AutoMapper 配置为使用 DerivedChild
实例自动映射 Child Value
属性 吗?假设的映射看起来像这样:
map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
.ForMember(p => p.Value, p => p.UseDestinationType<DerivedChild>());
(我是 projecting from LINQ entities. The closest I could find is using a custom type converter,但看起来我需要覆盖 整个 映射。)
您可以在映射后手动 re-assign 新建对象:
Mapper.CreateMap<ParentEntity, Parent>()
.AfterMap((src, dest) => dest.Value = new DerivedChild(){...});
甚至re-map它:
.AfterMap((src, dest) => dest.Value = Mapper.Map<DerivedChild>(dest.Value));
这是一种方法:
map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
.ForMember(
x => x.Value,
opt => opt.ResolveUsing(
rr => map.Map<DerivedChild>(((ParentEntity)rr.Context.SourceValue).Value)));
ResolveUsing
允许指定映射值的自定义逻辑。
这里使用的自定义逻辑实际上是调用map.Map
映射到DerivedChild
。
使用 AutoMapper,我可以覆盖 属性 的解析类型吗?例如,给定这些 类:
public class Parent
{
public Child Value { get; set; }
}
public class Child { ... }
public class DerivedChild : Child { ... }
我可以将 AutoMapper 配置为使用 DerivedChild
实例自动映射 Child Value
属性 吗?假设的映射看起来像这样:
map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
.ForMember(p => p.Value, p => p.UseDestinationType<DerivedChild>());
(我是 projecting from LINQ entities. The closest I could find is using a custom type converter,但看起来我需要覆盖 整个 映射。)
您可以在映射后手动 re-assign 新建对象:
Mapper.CreateMap<ParentEntity, Parent>()
.AfterMap((src, dest) => dest.Value = new DerivedChild(){...});
甚至re-map它:
.AfterMap((src, dest) => dest.Value = Mapper.Map<DerivedChild>(dest.Value));
这是一种方法:
map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
.ForMember(
x => x.Value,
opt => opt.ResolveUsing(
rr => map.Map<DerivedChild>(((ParentEntity)rr.Context.SourceValue).Value)));
ResolveUsing
允许指定映射值的自定义逻辑。
这里使用的自定义逻辑实际上是调用map.Map
映射到DerivedChild
。