Mapping 当源复杂时,将域类展平到ViewModel

Mapping 当源复杂时,将域类展平到ViewModel,mapping,valueinjecter,Mapping,Valueinjecter,我正在使用ValueInjector将域类映射到视图模型。我的域类很复杂。借用以下例子: 我已经看过FlatLoopInjection,但它希望视图模型类的前缀是嵌套的域模型类型,如下所示: public class PersonViewModel { public string FirstName { get; set; } public string LastName { get; set; } public int Id { get; set; } public i

我正在使用ValueInjector将域类映射到视图模型。我的域类很复杂。借用以下例子:

我已经看过FlatLoopInjection,但它希望视图模型类的前缀是嵌套的域模型类型,如下所示:

public class PersonViewModel
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Id { get; set; }
   public int AddressId { get; set; }
   public string AddressCity { get; set; }
   public string AddressState { get; set; }
   public string AddressZip { get; set; } 
}

链接问题中的OP修改了他的视图模型,以符合FlatLoopInjection预期的约定。我不想那样做。
如何将域模型映射到原始视图模型?我怀疑我需要覆盖FlatLoopInjection以删除前缀,但我不确定在哪里执行此操作。我已经查看了FlatLoopInjection的源代码,但我不确定是否需要更改Match方法或SetValue方法。

如果不需要展平,请先添加贴图:

Mapper.AddMap<Person, PersonViewModel>(src =>
{
    var res = new PersonViewModel();
    res.InjectFrom(src); // maps properties with same name and type
    res.InjectFrom(src.Address);
    return res;
});
Mapper.AddMap(src=>
{
var res=新PersonViewModel();
res.InjectFrom(src);//映射具有相同名称和类型的属性
res.From(src.地址);
返回res;
});
然后你可以打电话:

var vm = Mapper.Map<PersonViewModel>(person);
var vm=Mapper.Map(个人);

谢谢。无法看到树的林。虽然这样做有效,但实际上我的模型更复杂,有时不仅仅由一个子对象组成,因此映射包含大量手动代码来映射子类。即使源属性是嵌套的,我也可以尝试创建映射具有相同名称和类型的属性的注入。FlatLoopInjection中的一些代码看起来很有前途。请记住,您可以在
AddMap
内部调用
Mapper.Map
,谢谢。我想知道,并打算尝试一下。感谢您创建此映射器。
var vm = Mapper.Map<PersonViewModel>(person);