简体   繁体   English

实体框架和SQL Server中的DateTime格式

[英]DateTime format in Entity Framework and SQL Server

I am fetching datetime from SQL Server using Entity Framework. 我正在使用实体框架从SQL Server获取日期时间。 The format in my database is 2013-01-01 00:00:00.000 where as when I get it via Entity Framework in JSON format, it is "\\\\/Date(1356980400000+0500)\\\\/" . 我数据库中的格式为2013-01-01 00:00:00.000 ,其中当我通过Entity Framework以JSON格式获取它时,它的格式为"\\\\/Date(1356980400000+0500)\\\\/"

Here is my code 这是我的代码

public class SurveyData
{       
        [DataMember]
        public DateTime? CreatedDate { get; set; } 
}

var surveyDataList = (from survey in context.FDT_SURVEY                             
                      where survey.Name == surveyName 
                      select new SurveyData
                          {
                              SurveyID = SqlFunctions.StringConvert((double)survey.SURVEY_ID).Trim(),
                              CreatedDate = survey.CREATED_DATE,
                          }
    );

in my database, the datatype of CREATED_DATE is datetime . 在我的数据库中, CREATED_DATE的数据类型为datetime

Unable to understand what is the issue. 无法了解问题所在。 Any help ! 任何帮助!

Try this: 尝试这个:

    [DisplayFormat(DataFormatString = "{0,d}")]
    [DataType(DataType.DateTime)]
    public DateTime? CreatedDate { get; set; } 

Entity Framework doesn't return anything in JSON format. 实体框架不会以JSON格式返回任何内容。 It populates .NET objects with data, or populates databases with data from .NET objects. 它用数据填充.NET对象,或用.NET对象的数据填充数据库。 Attaching the debugger would show that the CreatedDate has the correct value in it, I believe. 我相信,附加调试器将显示CreatedDate具有正确的值。

The actual problem is more likely to do with the fact that JSON has no concept of a "date" or "datetime" type, despite the comments on the question. 实际问题更可能与以下事实有关:尽管对问题发表了评论,但JSON没有“日期”或“日期时间”类型的概念。 See The "right" JSON date format . 请参阅“正确的” JSON日期格式 Some serialization code is taking the .NET SurveyData class and serializing it to JSON using the .NET framework's JSON serializer (possibly the DataContractJsonSerializer ) and this is writing it out in the format you are seeing. 一些序列化代码采用.NET SurveyData类,并使用.NET框架的JSON序列化器(可能是DataContractJsonSerializer )将其序列化为JSON,并以您看到的格式将其写入。 This might be WCF or else an older version of ASP.NET MVC or Web API. 这可能是WCF,或者是ASP.NET MVC或Web API的旧版本。

Later versions of ASP.NET use the NewtonSoft JSON.net library to perform serialization of objects. 更高版本的ASP.NET使用NewtonSoft JSON.net库执行对象的序列化。 By default these use the ISO 8601 format, which is what most of the world expects in a JSON object for a date or datetime field. 默认情况下,它们使用ISO 8601格式,这是世界上大多数人期望的JSON对象中用于date或datetime字段的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM