2013-10-13 57 views
0

淨,我正在開發一個.net應用程序。我收到以下例外

我收到以下錯誤,我不知道什麼是錯我的代碼

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

這是我的代碼,其中的例外來了。

public List<ToureDeieselBean> loadDeiselListOnTourUpDownId(int tourUpDownId) 
    { 
     return (from p in context.tb_tourDiesel 
       where p.deleted == 0 
       where p.tourUpDownId == tourUpDownId 
       select new ToureDeieselBean 
       { 
        id = p.id, 
        qty =(float)p.qty, 
        ratePerlt = (float)p.ratePerlt, 
        createdBy = p.createdBy, 
        createdOn = p.createdOn==null?"":(p.createdOn).ToString(), 
        updatedBy = p.updatedBy, 
        updatedOn = p.updatedOn == null ? "" :(p.updatedOn).ToString(), 
        descrption=p.descrption, 
        deleted=Convert.ToBoolean(p.deleted) 
       }).ToList<ToureDeieselBean>(); 
    } 
+1

變化'createdOn'和'updatedOn'爲DateTime類型和不使用'的ToString()'(這並不適用於所有LINQ提供工作) –

+0

您可以使用方法語法沒有任何問題。恕我直言,LINQ不能識別查詢sntax中的ToString()。 –

+0

@ Joachim Isaksson如果我更改createdOn和updatedOn到DateTime,那麼它不接受空值 –

回答

0

您可以通過使用去除ToString和更長的三元運營商null coalescing operator

public List<ToureDeieselBean> loadDeiselListOnTourUpDownId(int tourUpDownId) 
{ 
     return (from p in context.tb_tourDiesel 
       where p.deleted == 0 
       where p.tourUpDownId == tourUpDownId 
       select new ToureDeieselBean 
       { 
        id = p.id, 
        qty =(float)p.qty, 
        ratePerlt = (float)p.ratePerlt, 
        createdBy = p.createdBy, 
        createdOn = p.createdOn ?? "", 
        updatedBy = p.updatedBy, 
        updatedOn = p.updatedOn ?? "", 
        descrption=p.descrption, 
        deleted=Convert.ToBoolean(p.deleted) 
       }).ToList<ToureDeieselBean>(); 
} 
0

當你與EF LINQ查詢工作被翻譯成SQL,而當你在LINQ使用的此類方法沒有按在SQL中不存在這個異常。

這將工作:

var temp=(from p in context.tb_tourDiesel 
       where p.deleted == 0 
       where p.tourUpDownId == tourUpDownId).ToList<ToureDeieselBean>(); 

     return (from p in temp 
       select new ToureDeieselBean 
       { 
        id = p.id, 
        qty = (float)p.qty, 
        ratePerlt = (float)p.ratePerlt, 
        createdBy = p.createdBy, 
        createdOn = p.createdOn == null ? "" : (p.createdOn).ToString(), 
        updatedBy = p.updatedBy, 
        updatedOn = p.updatedOn == null ? "" : (p.updatedOn).ToString(), 
        descrption = p.descrption, 
        deleted = Convert.ToBoolean(p.deleted) 
       }).ToList(); 
相關問題