6
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."}

Joakim
  • 2,217
  • 15
  • 20
Ronald
  • 1,532
  • 4
  • 18
  • 34

3 Answers3

17

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(),
        [...]
    })
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
2

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.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • I feel that is what I will do, make PostingDate as DateTime type. I wanted to save the client from having to perform the date formatting, but it looks like it can't be helped in this case. – Ronald Jul 31 '11 at 06:10
0

I dont think this can be done in a direct way.

   var list =    
    select new Post { Username = u.Username, PostingDate =  SqlFunctions.StringConvert(c.Date), Data = c.Comment } 
from 
(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).AsEnumerable()  
    ).ToList();

Also with EF4 you can try something like this:

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 = SqlFunctions.DateName(c.Date), Data = c.Comment }
).ToList();
Baz1nga
  • 15,485
  • 3
  • 35
  • 61