C# 更改lambda表达式中的日期时间格式
我有一个日期时间格式的DTO字段C# 更改lambda表达式中的日期时间格式,c#,linq,datetime,lambda,C#,Linq,Datetime,Lambda,我有一个日期时间格式的DTO字段 public DateTime date_joined { get; set; } 我使用它将数据转换为Json public JsonResult Customer(int? id) { var user = User.Identity.Name; if (!AccountController.IsInRole(user, "admin")) {
public DateTime date_joined { get; set; }
我使用它将数据转换为Json
public JsonResult Customer(int? id)
{
var user = User.Identity.Name;
if (!AccountController.IsInRole(user, "admin"))
{
return null;
}
id = id == null ? 0 : id;
var customer = db.PrmCustomers
.Where(x => x.EmailAddress != null && x.CustomerID > id)
.OrderBy(x => x.CustomerID)
.Select(x => new CustomerDTO()
{
email = x.EmailAddress,
phone = x.MobilePhoneNumber,
username = "",
first_name = x.Name,
last_name = x.Surname,
gender = x.GenderType,
customer_code = x.CustomerID,
is_active = "",
//date_joined = String.Format("{0:d/M/yyyy HH:mm:ss}", x.CreateDate.ToString()),
date_joined = x.CreateDate,
last_login = "",
date_of_birth = x.BirthDate,
//date_of_birth = String.Format("{0:d/M/yyyy HH:mm:ss}", x.BirthDate.ToString()),
password = x.Password,
email_allowed = x.IsNewsletter,
sms_allowed = x.IsSms,
verified = x.IsApprovedEmail,
social_account_facebook_uuid = "",
social_account_facebook_extra = ""
});
return Json(customer, JsonRequestBehavior.AllowGet);
}
问题是,结果是这样的
"date_joined":"\/Date(1516965473683)\/"
我试着把它改成另一种格式,但到目前为止我无法管理它
首先,我尝试了通常的日期时间格式,如toString(“newFOrmat”)
,但我遇到了Linq错误,主要是因为在SQL Server中无法识别toString()
然后我遇到了这个问题,并尝试了这个方法
return Json(customer.AsEnumerable().Select(r=>new CustomerDTO{
date_joined = r.date_joined.GetValueOrDefault().ToString("dd.MM.yyyy")
}) , JsonRequestBehavior.AllowGet);
我得到了“DateTime没有GetValueOf()的定义”错误,尽管我包含了正确的名称空间
省略它并仅使用通常的ToString(“格式”)会导致上面的Linq错误
还有其他建议吗
编辑:我的DTO和输出还有其他字段。我没有将它们包括在问题中。我认为您最好的选择是通过调用.ToList()
从数据库加载所需的数据,然后将该数据映射到您的DTO。
确保将DTO上的类型从DateTime
更改为string
大概是这样的:
public JsonResult Customer(int? id)
{
var user = User.Identity.Name;
if (!AccountController.IsInRole(user, "admin"))
{
return null;
}
id = id == null ? 0 : id;
var customer = db.PrmCustomers
.Where(x => x.EmailAddress != null && x.CustomerID > id)
.OrderBy(x => x.CustomerID).ToList() // <-- ToList executes the query
.Select(x => new CustomerDTO()
{
email = x.EmailAddress,
phone = x.MobilePhoneNumber,
username = "",
first_name = x.Name,
last_name = x.Surname,
gender = x.GenderType,
customer_code = x.CustomerID,
is_active = "",
date_joined = x.CreateDate.ToString("d/M/yyyy HH:mm:ss"),
//date_joined = x.CreateDate,
last_login = "",
//date_of_birth = x.BirthDate,
date_of_birth = x.BirthDate.ToString("d/M/yyyy HH:mm:ss"),
password = x.Password,
email_allowed = x.IsNewsletter,
sms_allowed = x.IsSms,
verified = x.IsApprovedEmail,
social_account_facebook_uuid = "",
social_account_facebook_extra = ""
});
return Json(customer, JsonRequestBehavior.AllowGet);
}
publicjsonresult客户(int?id)
{
var user=user.Identity.Name;
if(!AccountController.IsInRole(用户,“admin”))
{
返回null;
}
id=id==null?0:id;
var customer=db.prmccustomers
.Where(x=>x.EmailAddress!=null&&x.CustomerID>id)
.OrderBy(x=>x.CustomerID).ToList()//新CustomerTo()
{
email=x.EmailAddress,
phone=x.MobilePhoneNumber,
用户名=”,
first_name=x.name,
姓氏=x.姓,
性别=x.GenderType,
客户代码=x.CustomerID,
_是否处于活动状态“”,
date_joined=x.CreateDate.ToString(“d/M/yyyy HH:mm:ss”),
//加入日期=x.CreateDate,
上次登录=”,
//出生日期=x.出生日期,
出生日期=x.BirthDate.ToString(“d/M/yyyy HH:mm:ss”),
密码=x.密码,
允许发送电子邮件=x.ISN时事通讯,
sms_允许=x.IsSms,
已验证=x.IsApprovedMail,
社交账户、facebook、uuid=“”,
社交账户facebook额外=“”
});
返回Json(customer,JsonRequestBehavior.AllowGet);
}
因此基本上需要调用数据库函数将日期转换为字符串
有一个很棒的库可以帮助将数据库函数和存储过程映射到实体框架
我将下面的代码或多或少地更改为您需要的代码,这些代码用于将字符串转换为int。因此,在更改为DateTime函数时可能会出现一些小错误
你可以考虑映射SQL的“格式”函数,然后你可以从LINQ传递日期格式,但是在下面的例子中,我假设你在SQL中创建了一个函数,名为<代码> DATEYToToSoist
安装Nuget软件包
- Install-Package EntityFramework.Functions
为函数创建扩展方法:
public static class SQLFunctions
{
[Function(FunctionType.BuiltInFunction, "DATE_TO_STRING")]
public static string SqlDateToString(this DateTime value) => Function.CallNotSupported<string>();
}
在LINQ查询中调用新映射的“SqlDateToString()”函数:
.Select(p => p.YourDateColumn.SqlDateToString());
还有你叔叔
另一个选择是使用MomentJs,它可以很好地理解json日期格式,然后您就不需要这种映射了。我不喜欢公认的答案;
我建议您扩展JsonResult(通过谷歌搜索,您可以找到许多使用这种方法的帖子),并覆盖ExecuteSult方法:
public class JsonNetResult : JsonResult
{
public object Data { get; set; }
public JsonNetResult()
{
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };
JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings());
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
最后:
return new JsonNetResult() { Data = customer };
这段代码以ISO格式返回日期在我看来,这段日期格式来自对JSON的转换。请参阅Json.Net文档。我不知道为什么要使用JsonResult
,但如果这是Web API(2或核心),您可以轻松更改代码样式,这样您就不必再担心Json(反)序列化了。谢谢,虽然我也需要将DTO的类型更改为字符串,但这很有效。我认为,这不是解决问题的正确方法。您可以修改web api json序列化程序设置以保持所需的格式。
return new JsonNetResult() { Data = customer };