无法隐式转换类型System.DateTime?'到' System.DateTime'使用EFW和ViewModel插入数据库时

时间:2018-03-23 18:49:47

标签: asp.net-mvc entity-framework asp.net-core-mvc viewmodel asp.net-mvc-viewmodel

我正在处理这个{ "took": 1, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 20967, "max_score": 1, "hits": [ { "_index": "catalog-2018-03-03", "_type": "product", "_id": "151755703145e27e4983a0bd1b70be44", "_score": 1, "_source": { "merchant": { "link": "http://shophive.com/", "name": "shophive" }, "images": [ { "url": "http://www.shophive.com/media/catalog/product/cache/1/small_image/165x/9df78eab33525d08d6e5fb8d27136e95/p/l/plantronics_savi_talk.jpg", "path": "full/8e3587bd2b6107f0beafa9b1ba05f476539be0a8.jpg", "checksum": "fa74ade23c8e80e9590d48d4e59b6b64" } ], "updated": "2018-03-18T13:06:33.583480", "name": "Plantronics Savi Talk", "created": "2018-03-18T13:06:33.583459", "url": "http://www.shophive.com/plantronics-savi-talk", "price": { "new": 24999, "old": 24999, "discount_percent": 0 }, "category": { "level_1": { "url": "computers/tablets/networking", "name": "Computers/Tablets & Networking " }, "level_2": { "url": "tablets/ebook-readers", "name": "Tablets & eBook Readers" } } } } } } 项目,当我收到此错误时,我尝试将值从ASP.NET Core MVC保存到form

  

无法隐式转换类型System.DateTime?'到' System.DateTime'。存在显式转换(您是否错过了演员?)

我在{ViewModel:

中以下列方式使用DatabaseFromDateToDate设为nullable

视图模型:

?

public class ILViewModel { ... ... public DateTime? FromDate { get; set; } public DateTime? ToDate { get; set; } } 中,我将按以下方式向Controller - POST Method添加值:

控制器:

Database

怎么办?

1 个答案:

答案 0 :(得分:0)

您需要从可空对象中获取值。然后你不会得到错误

if (ModelState.IsValid)
{
    ...
    historyObj.FromDate = locationsHistoryVM.FromDate.Value;
    historyObj.ToDate = locationsHistoryVM.ToDate.Value;
}