自动映射器,映射到接口 [英] automapper, mapping to an interface

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

问题描述

我正在使用自动映射器(对于.net 3.5).这是一个示例,说明我正在尝试做的事情:

I am using automapper (for .net 3.5). Here is an example to illustrate what I am trying to do:

我想将A对象映射到B对象.类定义:

I want to map an A object to a B object. Class definitions:

class A
{
    public I1 MyI { get; set; }

}
class B
{        
    public I2 MyI { get; set; }
}

interface I1
{
    string StringProp1 { get; }
}
interface I2
{
    string StringProp1 { get; }
}

class CA : I1
{
    public string StringProp1
    {
        get { return "CA String"; }
    }
    public string StringProp2 { get; set; }
}
class CB : I2
{
    public string StringProp1
    {
        get { return "CB String"; }
    }
    public string StringProp2 { get; set; }
}

映射代码:

        A a = new A()
        {
            MyI = new CA()
        };
        // Mapper.CreateMap ...?
        B b = Mapper.Map<A,B>(a);

我希望用CB实例填充结果对象b.因此,自动映射器需要知道A映射到B,CA映射到CB,并且在创建B填充时,它是带有CB的MyI prop,如何指定此映射?

I want the resulting object b to be populated with an instance of CB. So automapper needs to know that A maps to B, CA maps to CB, and when creating a B populate it's MyI prop with a CB, how do I specify this mapping?

推荐答案

类似以下内容:

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(x => x.AddProfile<MappingProfile>());

        var a = new A()
        {
            MyI = new CA()
            {
                StringProp2 = "sp2"
            }
        };

        var b = Mapper.Map<A, B>(a);

        Console.WriteLine("a.MyI.StringProp1: " + a.MyI.StringProp1);
        Console.WriteLine("b.MyI.StringProp1: " + b.MyI.StringProp1);

    }
}

> = AutoMapper 2.0.0

>= AutoMapper 2.0.0

public class MappingProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<CA, CB>();
        CreateMap<CA, I2>().As<CB>();                                                                       
        CreateMap<A, B>();
    }
}

AutoMapper 1.1.0.188(.Net 3.5)

AutoMapper 1.1.0.188 (.Net 3.5)

public class MappingProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<CA, CB>();

        CreateMap<CA, I2>()
            .ConstructUsing(Mapper.Map<CA, CB>)
            ;

        CreateMap<A, B>();
    }
}

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

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