What is the correct way to get a sortable string from a DateTime in a LINQ entity?
// 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;
}
I'm using a JavaScript framework that开发者_Python百科 needs dates in ISO 8601 style format, which is exactly what calling .ToString("s")
on a DateTime
object will return.
Is there a cleaner/more efficient way to do this in LINQ to SQL?
I believe the Wrapper
trick is as good as you can get in this situation. Sorry.
Update: Seems this has been asked again here: Linq to Sql - DateTime Format - YYYY-MMM (2009-Mar). The answer was pretty much "sorry" there too; considering who participated in that question, I 'm now really sure that you can't do better.
The problem is that, when using IQueryable
, the provider tries to translate all of the LINQ expressions into something it can send down to the database. It has no way of knowing what to do with ToString("s")
, so the NotSupported
exception is thrown.
If you were to add .AsEnumerable()
before the Select
call, then it should work. The difference is that the Person
object will be brought into memory completely, then the projection (the Select) method will be ran and all of that is done as a .NET compiled method, not as SQL. So essentially anything after AsEnumerable()
will be done in memory and not in the database, so it's generally not recommended to do until you've trimmed down the number of rows as much as possible (i.e. after all Where
and OrderBy
s).
精彩评论