在映射到视图模型时将字符串转换为日期时间

本文关键字:转换 字符串 日期 时间 映射 视图 模型 | 更新日期: 2023-09-27 17:56:53

我有一个MVC应用程序,我在其中收集日期时间字段(MM/dd/yyyy)作为字符串,以避免Chrome在引导程序中覆盖日期选择器,并避免在Excel的sqlbulk上传中进行映射。 我现在需要将此字符串字段映射回日期时间,并且正在为此苦苦挣扎。

这是我的模型:

public class Something
{
    [Key]
    public string SomeNumber { get; set; }
        ....
    public string SomeDate { get; set; }
    public string SomeOtherDate { get; set; }
        ....
}

和我的视图模型:

public class HistoricalDataVM
{
    .....
    [Display(Name = "Some Date")]
    public DateTime SomeDate { get; set; }
    [Display(Name = "Some Other Date")]
    public DateTime SomeOtherDate { get; set; }
    ....
}

和我的控制器操作:

[ChildActionOnly]
public PartialViewResult SomePartial()
{
    var vm = _ctx.Something.Select(p => new HistoricalDataVM()
    {
        ...
        SomeDate = DateTime.ParseExact(p.SomeDate, "MM/dd/yyyy", CultureInfo.InvariantCulture),
        SomeOtherDate = DateTime.ParseExact(p.SomeOtherDate, "MM/dd/yyyy", CultureInfo.InvariantCulture),
        ....
    }).OrderByDescending(c => c.SomeDate).ToList();
    return PartialView(vm);
}

我已经尝试了"转换"和DateTime.Parse,但都会导致"黄屏死机",并显示以下错误消息:

LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

我已经用谷歌搜索了SO,但找不到有效的解决方案。

任何帮助都非常感谢。 谢谢。

在映射到视图模型时将字符串转换为日期时间

您需要首先将查询具体化到应用程序,然后对其进行分析。实体框架不知道如何执行点网方法,它只知道如何将它们转换为 SQL

您可以使用DateTime.ParseExact()并设置严格的格式。https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

var datetime = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture);

它应该给你这样的东西:

[ChildActionOnly]
public PartialViewResult SomePartial()
{
    var vm = _ctx.Something.Select(p => new HistoricalDataVM()
    {
            SomeDate = DateTime.ParseExact(p.SomeDate, "MM/dd/yyyy", CultureInfo.InvariantCulture),
            SomeOtherDate = DateTime.ParseExact(p.SomeOtherDate, "MM/dd/yyyy", CultureInfo.InvariantCulture),
            ....
        }).OrderByDescending(c => c.SomeDate).ToList();
        return PartialView(vm);
    }