2013-01-08 69 views
9

我該如何重構此LINQ以使其工作?LINQ to Entities無法識別方法'System.String格式

var a = (from app in mamDB.Apps where app.IsDeleted == false 
       select string.Format("{0}{1}",app.AppName, 
       app.AppsData.IsExperimental? " (exp)": string.Empty)) 
       .ToArray();} 

我現在得到的錯誤:

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

我已經白白嘗試:

return (from app in mamDB.Apps where app.IsDeleted == false 
     select new string(app.AppName + (app.AppsData != null && 
     app.AppsData.IsExperimental)? " (exp)": string.Empty)).ToArray(); 
+1

http://stackoverflow.com/questions/10079990/linq-to-entities-does-not-recognize-the-method-system-string-formatsystem-stri – Thelonias

回答

17

你可以做string.Format回到LINQ到對象:

var a = (from app in mamDB.Apps where app.IsDeleted == false 
     select new {app.AppName, app.AppsData.IsExperimental}) 
     .AsEnumerable() 
     .Select(row => string.Format("{0}{1}", 
      row.AppName, row.IsExperimental ? " (exp)" : "")).ToArray(); 
+0

你不應該真正被調用' ToList'來**確保**查詢先執行? – James

+1

@詹姆斯不需要; 'AsEnumerable()'打破了'IQueryable <>'組合,這就是所需要的。 –

+0

我可能是錯的,但不會IEnumerable導致*整個*'mamDB.Apps'表被拉入內存,然後應用'where'子句? – James

0

試試這個

var a = (from app in mamDB.Apps where app.IsDeleted == false 
      select new {AppName = app.AppName, IsExperimental = app.AppsData.IsExperimental}) 
      .Select(app => string.Format("{0}{1}",app.AppName, 
      app.IsExperimental? " (exp)": string.Empty)) 
      .ToArray();} 
+0

,不會改變任何東西AFAIK,因爲EF仍然會嘗試處理組成的查詢 –

+1

所以我想你在你的答案中添加AsAnumerable。 – Dennis

+0

;這就是AsEnumerable()修復的內容 –

相關問題