簡體   English   中英

C#模型驗證拋出“無法從System.DateTime轉換為System.Array”

[英]C# Model validation throws “Cannot convert from System.DateTime to System.Array”

我正在嘗試使用LinqToExcel從excel插入到表中,當我調用時

ValidateModel(u);

它引發了一個異常:

無法從System.DateTime轉換為System.Array

我在viewmodel上使用DataAnnotations。

ViewModel中的日期時間:

[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime FECHA_ADQ { get; set; }

控制器:

foreach (var a in excel.Worksheet<ViewModel>(sheet.First())) 
{
    //Validations//
    try 
    {
        Context db = new Context();
        ViewModel u = a;
        ModelState.Clear();
        ValidateModel(u);

        //Insert//
    }
    catch(Exception)
    {
        // ...
    }
}

excel文件中的日期時間:

在此輸入圖像描述

這是它在調試器上的樣子:

在此輸入圖像描述

我無法用excel解決這個問題,所以我最終在映射到基本模型后驗證並且它工作正常。

ModelState.Clear();

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<ViewModel, Model>();
});

IMapper mapper = config.CreateMapper();
var inv = mapper.Map<ViewModel, Model>(u);

if (inv.FECHA_ADQ.Year <= 2005) {
    errors.AppendLine("Serial: " + a.SERIAL + " Error on Row: " + row + " Cause: Invalid Date.");
    counter++;
} else {
    ValidateModel(inv);
    Context.ModelDB.Add(inv);
    Context.SaveChanges();
}    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM