将属性自动映射到子属性的属性 [英] AutoMap a property to property of sub-property

查看:28
本文介绍了将属性自动映射到子属性的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的数据模型:

I have this simple data model:

// Model
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    .... Another values here ....
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
    .... Another values here ....
}

// ViewModel
public class PersonViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

我想(使用 AutoMapper)将 PersonViewModel 的值映射到相应的属性(其中 AutoMapper 发现该属性应该在根对象中还是在子对象中)-目的).请记住,AutoMapper 不应创建 Person 对象和 Address(必须手动创建对象以在自动映射之前填充其他属性),并且 AutoMapper 使用已存在的对象.例如:

I want to map (using AutoMapper) the values of PersonViewModel to the corresponding properties (where AutoMapper discovers if the property should be in the root object or inside the sub-object). Keeping in mind, AutoMapper should not create neither Person object nor Address (the objects must be created manually to fill another properties before auto mapping), and AutoMapper uses the already existed objects. For example:

var addressObj = new Address
{

    ... Filling some values...

};
var personObj = new Person
{

    Address = addressObj;
    ... Filling some values...

};

mapper.Map(personViewModelObj, personObj); // How to make this work for both Person and Address properties?

如何让自动映射同时适用于个人属性和地址属性?

How can I get that auto mapping to work for both person properties and address properties?

我应该添加两条映射规则(地址和人),并执行两次 mapper.Map() 吗?

Should I add two mapping rules (for address and for person), and execute mapper.Map() twice?

推荐答案

使用 @Jasen 评论我得到了它的工作.主要问题是我的映射方向相反.官方文档中的这句话解决了问题:

Using @Jasen comments I got it working. The main problem was that I am mapping in a reversed direction. This sentence in official documentation solves the problem:

Unflattening 仅针对 ReverseMap 配置.如果你想要unflattening,你必须配置Entity -> Dto 然后调用ReverseMapDto -> Entity.

Unflattening is only configured for ReverseMap. If you want unflattening, you must configure Entity -> Dto then call ReverseMap to create an unflattening type map configuration from the Dto -> Entity.

这是链接:

https://github.com/AutoMapper/AutoMapper/blob/master/docs/Reverse-Mapping-and-Unflattening.md

换句话说,为了不讨人喜欢地工作,我必须(或必须)朝这个方向映射:

In other words, to get unflattering to work, I have (or must) to map in this direction:

CreateMap<HierarchicalObject, FlattenedObject>()
    .ReverseMap();

这篇关于将属性自动映射到子属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆