【发布时间】:2011-03-16 19:01:42
【问题描述】:
// EmployeeService:
[WebMethod]
public List<Employee> GetEmployees()
{
return
(
from p in db.Persons
where p.Type == 'E'
select new Employee
{
Name = p.FullName,
//HireDate = p.CreationDate.ToString(),
// works, but not in the format I need
//HireDate = p.CreationDate.ToString("s"),
// throws a NotSupportedException
//HireDate = Wrapper(p.CreationDate),
// works, but makes me worry about performance
// and feel dead inside
}
).ToList<Employee>();
}
private String Wrapper(DateTime date)
{
return date.ToString("s");
}
// Elsewhere:
public class Employee
{
public String Name;
public String HireDate;
}
我使用的 JavaScript 框架需要 ISO 8601 样式格式的日期,这正是在 DateTime 对象上调用 .ToString("s") 将返回的内容。
在 LINQ to SQL 中有更简洁/更有效的方法吗?
【问题讨论】:
-
我的 0.02 美元:没有规定必须对同一事物进行显示和排序。这是你不应该的时候之一。返回一个日期时间。 JavaScriptSerializer 以专有格式处理这些。在 JS 中反序列化为 JS 日期。您的排序将起作用。
-
@Craig Stuntz:同意,虽然排序不是我真正的问题;这更多是 ExtJS 处理(尤其是解析)ISO 8601 的问题,比 .NET 的专有格式要干净得多。
.ToString("s")on Get 和TryParse()on Save 会减少头痛(在我的特定情况下)。 -
我们所做的(在 jQuery 中,但应该可移植到 Ext)是在返回的 JSON 上有一个反序列化过滤器,它查找 MS 格式并在反序列化期间将其替换为
Date。 -
@Craig Stuntz:您可能会考虑在某处发布该反序列化过滤器;我想看看。
标签: c# linq linq-to-sql linq-to-entities