Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ convert DateTime to string

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

like image 721
Ronald Avatar asked Jul 31 '11 05:07

Ronald


People also ask

How do I convert DateTime to string?

In order to convert a DateTime to a string, we can use CONVERT() and CAST() function.

How to Convert Date format in LINQ?

DateCreated. ToString("yyyy-MM-dd hh:mm") });

How to Convert DateTime to Date in c#?

ToLongDateString() − Converts the value of the current DateTime object to its equivalent long date string representation. Returns a string that contains the long date string representation of the current DateTime object. ToString() − One more way to get the date from DateTime is using ToString() extension method.


2 Answers

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(),
        [...]
    })
like image 79
BrunoLM Avatar answered Nov 16 '22 19:11

BrunoLM


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.

like image 39
Anthony Pegram Avatar answered Nov 16 '22 19:11

Anthony Pegram