AutoMapper and reflection

旧巷老猫 提交于 2019-12-10 18:54:21

问题


My shared hosting company doesn't allow Reflection. How can I use AutoMapper?

Do I have to specify for each property a .ForMember?

Mapper.CreateMap<Person, PersonData>()
            .ForMember(dest => dest.Name, o => o.MapFrom(src => src.Name))
            .ForMember(dest => dest.Address, o => o.MapFrom(src => src.Address));

thanks,

Filip


回答1:


Automapper uses reflection.emit, are you sure you can use Automapper?

[Edit]

Dont know of any that uses without reflection, even the one I had created XmlDataMapper on CodePlex uses reflection. It would difficult to design one without reflection or reflection.emit

The simplest and basic way to do this would be this, you can use any of the two or both techniques.

public class ConversionHelper
{
   public static ClassB Convert(ClassA item)
   {
      return new ClassB() { Id = item.Id, Name = item.Name };
   }

   public static List<ClassB> Convert(List<ClassA> list)
   {
      return list.Select(o => new ClassB() { Id = o.Id, Name = o.Name }).ToList();
   }
}


public class ClassA
{
   public int Id { get; set; }
   public string Name { get; set; }
}
public class ClassB
{
   public int Id { get; set; }
   public string Name { get; set; }
}

From the sample you have given where you are anyways trying to map property one by one, this is on the same lines, but with lesser code.




回答2:


You cannot use Automapper or any other mapping architecture that I know of without reflection. This is logically obvious. How could you map two unknown entities to one another without using any of their reflected properties? Your only option in this case is to create a custom package to convert one object into another.




回答3:


Not at all. AutoMapper did a great job on intelligent mapping. If the property name of your source and destination object is the same, AutoMapper will map this proprties automatically for you.



来源:https://stackoverflow.com/questions/4332554/automapper-and-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!