创建相同的两个对象类型之间的两个Automapper地图 [英] Create two Automapper maps between the same two object types

查看:133
本文介绍了创建相同的两个对象类型之间的两个Automapper地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AutoMapper在WCF服务来回报用户的对象。 用户具有如 AccountTeams 属性本身有子对象。所有的类都AutoMapper映射。

I am using AutoMapper in a WCF service to return User objects. User has properties such as AccountTeams which itself has child objects. All of the classes have AutoMapper maps.

根据WCF OperationContract的即是所谓的,我想返回不同的数据。我想要一个 OperationContract的返回用户对象,而它的 AccountTeams 属性(及其子女)填充,另一个 OperationContract的返回用户与性能的全产业链填写。

Depending on the WCF OperationContract that is called, I want to return different amounts of data. I want one OperationContract to return the User object without its AccountTeams property (and their children) populated and another OperationContract to return the User with the whole chain of properties filled out.

有没有办法有两个相同的物体之间的两个不同的地图,或是否需要进行完整的映射和出的属性我不想从服务回报?

Is there a way to have two different maps between the same two objects or do I need to perform the full mapping and null out the properties I don't want to return from the service?

推荐答案

我假设你是从用户映射到用户(如果没有则只是更改了目标类型)

I am assuming you are mapping from User to User (if not then just change the destination type)

假设这个类下面的例子:

Assume this class for the following example:

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

您可以再使用单独的 AutoMapper.Configuration 来定义2图:

You can then use separate AutoMapper.Configuration to define 2 maps:

[TestMethod]
public void TestMethod()
{
    var configuration1 = new Configuration(new TypeMapFactory(), MapperRegistry.AllMappers());
    var mapper1 = new MappingEngine(configuration1);
    configuration1.CreateMap<User, User>();

    var user = new User() { Name = "John", Age = 42 };
    var mappedUser1 = mapper1.Map<User, User>(user);//maps both Name and Age

    var configuration2 = new Configuration(new TypeMapFactory(), MapperRegistry.AllMappers());
    configuration2.CreateMap<User, User>().ForMember(dest => dest.Age, opt => opt.Ignore());
    var mapper2 = new MappingEngine(configuration2);

    var mappedUser2 = mapper2.Map<User, User>(user);
    Assert.AreEqual(0, mappedUser2.Age);//maps only Name
}

要避免映射所有其他类型两次,你可以添加,需要一个配置将映射,可以从用户,并呼吁该两个配置1 configuration2 CreateMap

To avoid mapping every other Type twice you could add a common method that takes a Configuration which maps everything that can be reached from User and call this on both configuration1 and configuration2 after the calls to CreateMap.

这篇关于创建相同的两个对象类型之间的两个Automapper地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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