【问题标题】:AutoMap a property to property of sub-property将属性自动映射到子属性的属性
【发布时间】:2018-04-24 23:02:02
【问题描述】:

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

// 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; }
}

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

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?

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

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

【问题讨论】:

标签: c# .net .net-core automapper


【解决方案1】:

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

仅为ReverseMap 配置了展开。如果要展开,则必须配置 Entity -> Dto 然后调用 ReverseMapDto -> Entity 创建展开类型映射配置。

这是链接:

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

换句话说,为了不讨人喜欢的工作,我必须(或必须)朝着这个方向发展:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 2019-07-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多