2011-02-06 26 views
6

Geçerli bir tarih olan bir dizim var, ancak bir dize ve bir dize olması gerekiyor. Ben bir tarih için otomatik haritası o çalıştığımda Ancak bir istisnaDizginin automapper'daki bir tarihe nasıl eşlenir?

Trying to map System.String to System.DateTime. 

Trying to map System.String to System.DateTime. 
Using mapping configuration for ViewModels.FormViewModel to Framework.Domain.Test 
Destination property: DueDate 
Missing type map configuration or unsupported mapping. 
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: AutoMapper.AutoMapperMappingException: Trying to map System.String to System.DateTime. 
Using mapping configuration for ViewModels.FormViewModel to 
Framework.Domain.Task 
Destination property: DueDate 
Missing type map configuration or unsupported mapping. 
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. 
Ben bir oto dönüştürmek yapacağını ümit

atar ama bazı nasıl yapılacağını söylememiz gerekir sanırım.

Dönüştürmeyi nasıl anlarım?

cevap

12

bir dönüştürücü bir eşleme oluşturma ve kullanma:

CreateMap<string, DateTime>().ConvertUsing<StringToDateTimeConverter>(); 

Dönüştürücü:

public class StringToDateTimeConverter: ITypeConverter<string, DateTime> 
{ 
    public DateTime Convert(ResolutionContext context) 
    { 
     object objDateTime = context.SourceValue; 
     DateTime dateTime; 

     if (objDateTime == null) 
     { 
      return default(DateTime); 
     } 

     if (DateTime.TryParse(objDateTime.ToString(), out dateTime)) 
     { 
      return dateTime; 
     } 

     return default(DateTime); 
    } 
} 

Denedim ama bu işe yaramazsa ve bilmiyorum şu nedenleri:

CreateMap<string, DateTime>().ForMember(d => d, opt => opt.MapFrom(x => DateTime.Parse(x))); 

Eğer birisi bunun neden işe yaramadığını biliyorsa, bana bildirin :)

+0

Böyle bir şey yapmayı bitirdim, yine de bir çözümleyici kullandım. Bir çevirici olduklarını bilmiyordum. Doğrulama yaptığımı düşündüğüm kadar çok kontrol yapmam. – chobo2

+6

Bir dönüştürücü kullanırsanız, tüm dizgi-> tarih dönüşümlerini, her yerde kullanır. Bir tane dahil etmeyi düşündüm, ancak yerelleştirme vb. Için endişelenecek çok şey var. Çoğu zaman kullandığım: CreateMap (). ConvertUsing (Convert.ToDateTime); –

+0

@Jimmy Bogard - Neden CreateMap (). ForMember (d => d, opt => opt.MapFrom (DateTime.Parse)); çalışmıyor? – Rookian

İlgili konular