Оператор приведения не определен между типами 'System.String' и 'System.Nullable`1[System.DateTime]'
Я использую AutoMapper для отображения объектов. Иногда исходное значение равно нулю, поэтому я хочу заменить его на "", а не помещать NULL в базу данных. Исходный объект имеет много типов данных, которые могут иметь значение null, например Date, Decimal и Int. В настоящее время я использую
public class Invoice
{
public Guid Id { get; set; }
public string Number { get; set; }
public Contact Contact { get; set; }
public InvoiceType Type { get; set; }
public InvoiceStatus Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public DateTime? ExpectedPaymentDate { get; set; }
public DateTime? PlannedPaymentDate { get; set; }
public decimal? SubTotal { get; set; }
public decimal? TotalTax { get; set; }
public decimal? Total { get; set; }
public decimal? TotalDiscount { get; set;
public decimal? CurrencyRate { get; set; }
public DateTime? FullyPaidOnDate { get; set; }
public decimal? AmountDue { get; set; }
public decimal? AmountPaid { get; set; }
public decimal? AmountCredited { get; set; }
}
public partial class TempInvoice
{
public int RowId { get; set; }
public System.Guid InvoiceID { get; set; }
public string InvoiceNumber { get; set; }
public Nullable<System.Guid> ContactID { get; set; }
public string Type { get; set; }
public string Status { get; set; }
public string LineAmountType { get; set; }
public Nullable<System.DateTime> InvoiceDate { get; set; }
public Nullable<System.DateTime> DueDate { get; set; }
public Nullable<System.DateTime> ExpectedPaymentDate { get; set; }
public Nullable<System.DateTime> PlannedPaymentDate { get; set; }
public Nullable<decimal> SubTotal { get; set; }
public Nullable<decimal> TotalTax { get; set; }
public Nullable<decimal> Total { get; set; }
public Nullable<decimal> TotalDiscount { get; set; }
public Nullable<decimal> CurrencyRate { get; set; }
public Nullable<System.DateTime> FullyPaidOnDate { get; set; }
public Nullable<decimal> AmountDue { get; set; }
public Nullable<decimal> AmountCredited { get; set; }
}
public class InvoiceMapper : Profile
{
public InvoiceMapper()
{
CreateMap<Invoice, TempInvoice>()
.ForMember(des => des.PaymentID, map => map.MapFrom(src => src.Id))
.ForMember(des => des.InvoiceID, map => map.MapFrom(src => src.Invoice.Id))
.ForMember(des => des.PaymentDate, map => map.MapFrom(src => src.Date))
.ForAllMembers(src => src.NullSubstitute(""))//this doesn't work
;
}
}
Но я получаю вышеуказанную ошибку. Есть ли способ, которым я могу исключить тип datatime и установить int или decimal в 0 и строку в ""? Есть ли общий метод, который я могу использовать для всех типов данных? Спасибо
2 ответа
Вы можете использовать функцию распознавателя с ResolveUsing, используя собственную настраиваемую функцию отображения, которая возвращает пустую строку, если местом назначения является строка, в противном случае - ноль.
Например:
private static object MyMapperResolver(object source, bool returnEmptyString = true) {
return source ?? (returnEmptyString ? "" : source);
}
public static IMapper InitMappings() {
Mapper.Initialize(cfg => {
cfg.CreateMap<Invoice, TempInvoice>()
.ForMember(des => des.PaymentID, map => map.ResolveUsing(src => MyMapperResolver(src.Id)))
.ForMember(des => des.InvoiceID, map => map.ResolveUsing(src => MyMapperResolver(src.Invoice.Id)))
.ForMember(des => des.PaymentDate, map => map.ResolveUsing(src => MyMapperResolver(src.Date, false)))
;
});
return Mapper.Instance;
}
Вы можете использовать
AddTransform
public class InvoiceMapper : Profile
{
public InvoiceMapper()
{
CreateMap<Invoice, TempInvoice>()
.ForMember(des => des.PaymentID, map => map.MapFrom(src => src.Id))
.ForMember(des => des.InvoiceID, map => map.MapFrom(src => src.Invoice.Id))
.ForMember(des => des.PaymentDate, map => map.MapFrom(src => src.Date))
.AddTransform<string>(s => string.IsNullOrWhiteSpace(s) ? "" : s); // this line
}
}