简体   繁体   English

Automapper中的通用映射

[英]Generic mapping in Automapper

Im trying to use automapper to convert Data Contracts to Client objects and vice versa.to reduce the lines of code and to make it simpler I want to create mapping dynamically. 我试图使用自动映射器将数据协定转换为客户端对象,反之亦然。以减少代码行并使之简化,我想动态创建映射。 Lets say I'm calling 5 different services and each service will return same object like Employee but data will be different(If I need employee info from Microsoft I will call Microsoft service or if I want IBM employee details I will call IBM service so on). 可以说我正在调用5个不同的服务,每个服务将返回与Employee类似的对象,但数据将有所不同(如果我需要Microsoft的员工信息,我将调用Microsoft服务,或者如果我想要IBM员工详细信息,我将调用IBM服务,依此类推)。

My object is something like below.. 我的对象如下所示。

Public class Employee
{
Public string Id{get;set;}
Public string Division{get;set;}
Public PersonDetails person{get;set;}
}
Public class PersonDetails
{
Public string Name{get;set;}
Public string Email{get;set;}
Public string contact{get;set;}
}

Using Automapper I can write something below.. 使用Automapper,我可以在下面写一些东西。

 Mapper.CreateMap<Service1. PersonDetails, PersonDetails >();
   Mapper.CreateMap<Service1.Employee, Employee>()
        .ForMember(DEST=>DEST. PersonDetails,M=>M.MapFrom(Q=>Q. PersonDetails));
   Mapper.CreateMap<Service2. PersonDetails, PersonDetails >();
   Mapper.CreateMap<Service2.Employee, Employee>()
         .ForMember(DEST=>DEST.PersonDetails,M=>M.MapFrom(Q=>Q. PersonDetails));

ButI have to write same similar logic 5 times since i'm calling 5 different services. 但是自从我调用5种不同的服务以来,我不得不写5次相同的相似逻辑。

Is there any way I can do this dynamically meaning i want to tell Automapper about source at runtime.. 有什么办法可以动态地做到这一点,这意味着我想在运行时告诉Automapper有关源的信息。

Please advise!!! 请指教!!!

looks like you should be able to map from an interface instead of the service itself. 看起来您应该能够从接口而不是服务本身进行映射。

public interface IEmployeeServiceResponce
{
    Employee {get;}
    PersonDetails{get;}
}

then have each service implement that interface. 然后让每个服务实现该接口。

This articular may articulate my suggestion a little more 这个关节可能更能表达我的建议

if the return is not identical to the interface then I would recommend implementing the Adapter Patter to uniform them. 如果返回的信息与接口的信息不同,那么我建议实现Adapter Patter来统一它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM