Laziale
Laziale

Reputation: 8225

using ToString() in linq expression to convert DateTime value

I'm trying to convert a DateTime value to a string, but I'm getting this runtime error:

Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

This is the query I'm using:

using (var db = new DbContext())
{
    var results = (from u in db.AspNetUserses
        join upi in db.UserPersonalInfoes on u.Id equals upi.UserId into upis
        from upi in upis.DefaultIfEmpty()
        join up in db.UserPreferenceses on u.Id equals up.UserId into ups
        from up in ups.DefaultIfEmpty()
                   join us in db.UserStatses on u.Id equals us.UserId into uss
                   from us in uss.DefaultIfEmpty()
        select new
        {
            Username = u.UserName,
            Telephone = (upi == null ? String.Empty : upi.Telephone),
            ID = u.Id,
            LastLogin = (us == null ? String.Empty : us.LastLoginDate) 
        }).ToList();

    gvUsers.DataSource = results;
    gvUsers.DataBind();

}

Any idea how can I fix this error?

Upvotes: 0

Views: 1448

Answers (1)

Marko Juvančič
Marko Juvančič

Reputation: 5890

Create a second list and do the transformation there.

using (var db = new DbContext())
{
    var results = (from u in db.AspNetUserses
        join upi in db.UserPersonalInfoes on u.Id equals upi.UserId into upis
        from upi in upis.DefaultIfEmpty()
        join up in db.UserPreferenceses on u.Id equals up.UserId into ups
        from up in ups.DefaultIfEmpty()
               join us in db.UserStatses on u.Id equals us.UserId into uss
               from us in uss.DefaultIfEmpty()
        select new
        {
            Username = u.UserName,
            Telephone = (upi == null ? String.Empty : upi.Telephone),
            ID = u.Id,
            LastLogin = (us == null ? DateTime.MinValue : us.LastLoginDate) 
        }).ToList();

       var list = (from r in results
                   select new {
                     Username = r.UserName,
                     Telephone = r.Telephone,
                     ID = r.ID
                     LastLogin = r.LastLogin == DateTime.MinValue ? "" : r.LastLogin.ToString()
                    }).ToList();


      gvUsers.DataSource = list;
      gvUsers.DataBind();
}

Upvotes: 1

Related Questions