What's the easiest way to generate code dynamically in .NET 4.5?

前端 未结 4 1105
旧时难觅i
旧时难觅i 2020-12-31 23:41

I\'m writing a specific kind of object-mapper. Basically I want to convert from a DataTable that has the fields a, b and c

4条回答
  •  有刺的猬
    2021-01-01 00:23

    Sometimes a 3rd party library is the easiest way to do it, AutoMapper will do exactly what you want with just a few lines of code

    //This just needs to be run once, maybe in a static constructor somewhere.
    Mapper.CreateMap();
    
    
    
    //This line does your mapping.
    List myBusinessObject = 
        Mapper.Map>(myDataTable.CreateDataReader());
    

    If your source data does not exactly match your business object all you need to do is add some setup info to CreateMap.

    class MyBusinessObject
    {
        public int Answer;
        public string Question { get; set; }
    }
    
    //In some static constructor somewhere, this maps "a" to "Answer" and "b" to "Question".
    Mapper.CreateMap()
          .ForMember(dto => dto.Answer, opt => opt.MapFrom(rdr => rdr["a"]))
          .ForMember(dto => dto.Question, opt => opt.MapFrom(rdr => rdr["b"]));
    

提交回复
热议问题