创建相同的两个对象类型之间的两个Automapper地图 [英] Create two Automapper maps between the same two object types
问题描述
我使用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
}
要避免映射所有其他类型两次,你可以添加,需要一个配置
将映射,可以从用户到达的一切的一种常用方法code>,并呼吁该两个
。配置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屋!