简体   繁体   English

C#模型验证抛出“无法从System.DateTime转换为System.Array”

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

I'm trying to insert to a table from excel using LinqToExcel and when I call 我正在尝试使用LinqToExcel从excel插入到表中,当我调用时

ValidateModel(u);

It throws an exception: 它引发了一个异常:

Cannot convert from System.DateTime to System.Array 无法从System.DateTime转换为System.Array

I'm using DataAnnotations on the viewmodel. 我在viewmodel上使用DataAnnotations。

Datetime in ViewModel: ViewModel中的日期时间:

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

Controller: 控制器:

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)
    {
        // ...
    }
}

Datetime in excel file: excel文件中的日期时间:

在此输入图像描述

This is what it looks like on the debugger: 这是它在调试器上的样子:

在此输入图像描述

I couldn't resolve the issue with excel so i just ended up validating after the mapping to the base model and it worked. 我无法用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