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

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

问题描述

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

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:


仅针对 ReverseMap 配置了展开。如果要展平,则必须配置 Entity -> Dto ,然后调用 ReverseMap Dto -> 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天全站免登陆