2015-01-20 30 views
0

我想一個DateTime值轉換爲字符串,但我得到這個運行時錯誤轉換:在LINQ表達式中使用的ToString()來DateTime值

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

這是我的查詢使用:

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(); 

} 

任何想法如何解決這個錯誤?

+3

嗯,在那個代碼中你將'DateTime'轉換爲'string'?你的意思是寫'us.LastLoginDate.ToString()'? – 2015-01-20 19:57:43

+0

是的,多數民衆贊成我所嘗試的,對不起 – Laziale 2015-01-20 20:00:34

回答

1

創建第二個列表並在那裏進行轉換。

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(); 
} 
+0

是的.... LINQ鬥爭與轉換這樣的查詢。您也可以在第一次調用ToList()之後立即選擇(x => new {...},或者使用SqlFunctions.DateName,如下所示:[LINQ Date conversion](http://stackoverflow.com/questions/7999771/convert-datetime-to-string-inside-a-linq-query)。 – DrewJordan 2015-01-20 20:29:48

+0

Hvala ti @ marko-juvancic – Laziale 2015-01-20 20:33:40