DateTime to string conversion using LINQ

asp.net-mvc entity entity-framework linq

Question

List<Post> list =
(
    from c in db.TitleComments
    join t in db.Titles on c.TitleId equals t.Id
    join u in db.Users on c.UserId equals u.Id
    where t.Id == _titleId && c.Date > time
    orderby c.Date descending
    select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();

The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?

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

1
6
7/31/2011 8:20:16 AM

Accepted Answer

linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim

In other words, return the date itself and convert it to a string after it executes on SQL side:

(
select new { Username = u.Username,
    PostingDate = c.Date
    [...]
})
.ToList() // runs on SQL and returns to the application
.Select(o =>  // is not generating a SQL, it is running on the app
    new Post { Username = o.Username,
        PostingDate = o.PostingDate.ToString(),
        [...]
    })
17
7/31/2011 6:04:49 AM

Popular Answer

You can remedy your problem by projecting into an anonymous type, and then at a later step project into Post after the data has already been returned from the DB.

(from ....
 select new { /* stuff */, Date = c.Date })
.AsEnumerable()
.Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
.ToList();

However, given that you have a property called PostingDate, the original source being a date, I would recommend your revise your object to actually keep the value as a DateTime instead of a string.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow