c# - Best Practices for mapping one object to another -


my question is, best way can map 1 object in maintainable manner. cannot change way dto object getting setup more normalized need create way map our implementation of object.

here example code show need happen:

class program {     static void main(string[] args)     {         var dto = new dto();          dto.items = new object[] { 1.00m, true, "three" };         dto.itemsnames = new[] { "one", "two", "three" };                      var model = getmodel(dto);          console.writeline("one: {0}", model.one);         console.writeline("two: {0}", model.two);         console.writeline("three: {0}", model.three);         console.readline();     }      private static model getmodel(dto dto)     {         var result = new model();          result.one = convert.todecimal(dto.items[array.indexof(dto.itemsnames, "one")]);         result.two = convert.toboolean(dto.items[array.indexof(dto.itemsnames, "two")]);         result.three = dto.items[array.indexof(dto.itemsnames, "three")].tostring();          return result;     } }  class dto {     public object[] items { get; set; }     public string[] itemsnames { get; set; } }  class model {     public decimal 1 { get; set; }     public bool 2 { get; set; }     public string 3 { get; set; } } 

i think great if had sort of mapper class take in model objects propertyinfo, type want convert to, , "itemname" want pull out. have suggestions make cleaner?

thanks!

i opt automapper, open source , free mapping library allows map 1 type another, based on conventions (i.e. map public properties same names , same/derived/convertible types, along many other smart ones). easy use, let achieve this:

model model = mapper.map<model>(dto); 

not sure specific requirements, automapper supports custom value resolvers, should writing single, generic implementation of particular mapper.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -