自动映射器,映射到接口

编程入门 行业动态 更新时间:2024-10-28 01:21:56
本文介绍了自动映射器,映射到接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am using automapper (for 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>(); } }

更多推荐

自动映射器,映射到接口

本文发布于:2023-11-04 12:03:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!