gpt4 book ai didi

c# - 日期时间到字符串转换显示错误

转载 作者:行者123 更新时间:2023-12-02 14:19:49 25 4
gpt4 key购买 nike

我正在尝试使用自定义格式将 DateTime 转换为 string。但它向我显示 LINQ 错误

LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

这是我在 Controller 中的代码:

public ActionResult DaywiseData(DateTime date)
{
try
{
var att = db.Attendances
.Where(d => d.Date == date)
.Select(s => new AttendanceViewModel
{
Date = s.Date,
aa = DateTime.Parse(s.InTime.ToString()).ToString("HH:mm tt"), //Error is not showing after removing this line
InTime = s.InTime,
OutTime = s.OutTime,
EmployeeName = s.Employee.Name,
EmployeeUsername = s.Employee.Username
})
.ToList();
return Json(att);
}
catch (Exception ex)
{
return Json(ex.Message);
}
}

最佳答案

您的 LINQ 已转换为不支持 ToString() 的 SQL 查询。将其保留为 DateTime,稍后转换为字符串。像这样的事情

public ActionResult DaywiseData(DateTime date)
{
try
{
var att = db.Attendances
.Where(d => d.Date == date)
.Select(s => new AttendanceViewModel
{
Date = s.Date,
DateTime = s.InTime, //dateTime property
DateTimeString = string.Empty //string property
InTime = s.InTime,
OutTime = s.OutTime,
EmployeeName = s.Employee.Name,
EmployeeUsername = s.Employee.Username
})
.ToList();
att.ForEach(a => a.DateTimeString = a.DateTime.ToString("HH:mm tt"));

return Json(att);
}
catch (Exception ex)
{
return Json(ex.Message);
}
}

关于c# - 日期时间到字符串转换显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com