0

I'm using Mapster to map values from a dto based on a json object to a Entity Framework data table. The destination class has a field [Column(TypeName = "datetime2(3)")] public DateTime? CorrectBy { get; set; } that is being filled from a string representing a date. The string can be empty or "".

Is there a good mapping strategy for handling this using Mapster? My mapping currently looks like this:

TypeAdapterConfig<InModels.Violation, InspectionViolation>.NewConfig()
            .Map(d=>d.CorrectBy,s=>DateTime.Now,srcCond=>srcCond.CorrectBy=="")
            .Map(d => d.CorrectBy, s =>DateTime.Parse(s.CorrectBy))                
            .IgnoreNullValues(true);

but still throws an error saying that it can't convert "" to datetime.

John S
  • 7,909
  • 21
  • 77
  • 145

1 Answers1

1

Empty string is not supported converting to DateTime. You need to define custom string to datetime mapping.

TypeAdapterConfig<string, DateTime?>.NewConfig()
    .MapWith(src => string.IsNullOrEmpty(src) ? null : (DateTime?)DateTime.Parse(src));