automapper多对一映射 [英] automapper many to one mapping

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

问题描述

我想一种类型映射到其他,但我有在要求获得其他类型的一个特性,第一类多个属性。

i want to map one type to other but i have multiple properties in the first type that is required to get one property of other type

例如

public class A
{ 
    public int a{get;set;}
    public int b{get;set;}
    public int c{get;set}
}

public class B
{ 
    public C z{get;set;}
    public int c{get;set}
}

public class C
{ 
    public int a{get;set;}
    public int b{get;set;}
    public int Total{get;set}
}

public class D
{
    public C Get(A a)
    {
       var c = new C();
       c.a = a.a;
       c.b= b.a;
       c.c = c.a + c.b;
       return c
    }   
}



在这里我要地图A到b,那么,如何可以使用Automapper

here I want to map A to B, so how can i do it using Automapper

推荐答案

您可以使用 ForMember 从您的简单类型映射到复杂类型是这样的:

You can use ForMember to map from your simple types to your complex type like this:

AutoMapper.CreateMap<A,B>()
.ForMember(dest => dest.z.a, opt => opt.MapFrom(src => src.a));

您可以链尽可能多的 ForMember 。因为你需要调用

You can chain as many of these ForMember invocations as you need.

另一种方法是要为配置映射到C这样:

Another approach would be to configure a map for A to C such that:

AutoMapper.CreateMap<A,C>();



,然后从A你映射到B你可以说:

and then in your mapping from A to B you can say:

AutoMapper.CreateMap<A,B>()
.ForMember(dest => dest.z, opt => opt.MapFrom(src => src))

这告诉AutoMapper使用映射从A到C的成员ž从A到b
时做一个映射(因为的src 是一个实例和 DEST 是C的一个实例)

This tells AutoMapper to use the mapping from A to C for member z when doing a mapping from A to B (Since src is an instance of A and dest is an instance of C)

更新

如果您需要使用您的 D 获取的方法做你的映射从A到C然后你可以这样做使用AutoMapper的 ConstructUsing 方法。

If you need to use your D class' Get method to do your mappings from A to C then you can do so using the ConstructUsing method in AutoMapper.

AutoMapper.CreateMap<A,B>()
.ForMember(dest => dest.z, opt => opt.ConstructUsing(src => new D().Get(src));

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

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