2015-06-18 27 views
-1

我有一个MVC应用程序,其中我收集日期时间字段(MM/DD/YYYY)作为字符串,以避免铬覆盖在自举的日期选择器,并避免的Excel sqlbulk上传映射。我现在需要将这个字符串字段映射回日期时间,并且正在为此付出极大的努力。转换字符串在映射到DATETIME视图模型

这里是我的模型:

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. 

我已经Google搜索和搜索到,并找不到一个有效的解决方案。

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

+0

您可以显示'DateTime.Parse'或'/ Convert'代码示例吗? –

+1

供参考:您可以为浏览器提供自己的日期选择器功能测试,并防止在这些情况下应用引导程序。这是一个可以解决的问题。 –

+0

你是对的,科里,但仍然需要在sqlbulk方法中的映射,我大大缩短了什么是一个非常长的模型,所以这不是唯一的考虑因素。 – New2ASPMVC

回答

1

您需要查询第一兑现你的应用程序,然后解析它。实体框架不知道如何执行点网络方法,它只知道如何将它们转换为SQL

0

你可以使用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); 
    }