2015-04-01 12 views
8

मैंने स्टैक ओवरफ्लो पर खोज की है और इसके बारे में googled है, लेकिन मैं इस पर कोई मदद या सुझाव खोजने में सक्षम रहा है।ऑटोमैपर जेनेरिक मैपिंग

मैं की तरह एक वर्ग है जो निम्नलिखित एक PagedList वस्तु बना सकते हैं और भी AutoMappper का उपयोग करता है गंतव्य

public class PagedList<TSrc, TDest> 
{ 
    protected readonly List<TDest> _items = new List<TDest>(); 

    public IEnumerable<TDest> Items { 
     get { return this._items; } 
    } 
} 

के स्रोत से प्रकार मैप करने के लिए मैं इस प्रकार के लिए एक नक्शा है कि यह दूसरे में बदलने चाहिए बनाना चाहेंगे निम्नलिखित

public class PagedListViewModel<TDest> 
{ 
    public IEnumerable<TDest> Items { get; set; } 
} 

मैं

Mapper.CreateMap<PagedList<TSrc, TDest>, PagedListViewModel<TDest>>(); 
साथ की कोशिश की है की तरह टाइप

लेकिन संकलक TSrc और TDest

किसी भी सुझाव के कारण शिकायत करता है?

उत्तर

13

the AutoMapper wiki के अनुसार:

public class Source<T> { 
    public T Value { get; set; } 
} 

public class Destination<T> { 
    public T Value { get; set; } 
} 

// Create the mapping 
Mapper.CreateMap(typeof(Source<>), typeof(Destination<>)); 

आपके मामले में इस

Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>)); 
+0

करें संकलक' PagedList' पर एक त्रुटि के बारे में शिकायत है और कहता है 'सामान्य प्रकार PagedList उपयोग करने की आवश्यकता दो प्रकार arguments' – Lorenzo

+1

@Lorenzo (पेजेडलिस्ट <,>) 'कई सामान्य प्रकारों को इंगित करने के लिए। –

+0

बहुत बहुत धन्यवाद! – Lorenzo

0

होगा यह एक सबसे अच्छा अभ्यास है:

पहला कदम: एक generice वर्ग पैदा करते हैं।

public class AutoMapperGenericsHelper<TSource, TDestination> 
    { 
     public static TDestination ConvertToDBEntity(TSource model) 
     { 
      Mapper.CreateMap<TSource, TDestination>(); 
      return Mapper.Map<TSource, TDestination>(model); 
     } 
    } 

दूसरा कदम: typeof का उपयोग `: इसका इस्तेमाल

[HttpPost] 
     public HttpResponseMessage Insert(LookupViewModel model) 
     { 
      try 
      { 
       EducationLookup result = AutoMapperGenericsHelper<LookupViewModel, EducationLookup>.ConvertToDBEntity(model); 
       this.Uow.EducationLookups.Add(result); 
       Uow.Commit(User.Id); 
       return Request.CreateResponse(HttpStatusCode.OK, result); 
      } 
      catch (DbEntityValidationException e) 
      { 
       return Request.CreateResponse(HttpStatusCode.InternalServerError, CustomExceptionHandler.HandleDbEntityValidationException(e)); 
      } 
      catch (Exception ex) 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest, ex.HResult.HandleCustomeErrorMessage(ex.Message)); 
      } 

     } 
संबंधित मुद्दे