2013-06-05 91 views
0

我有以下例外。我檢查了設計師和班級,機會代碼是一個整數。將字符串轉換爲int時的特定linq異常。 LINQ to Entities不能識別方法'Int32 ToInt32(System.Object)'m

LINQ實體無法識別方法「的Int32 ToInt32(System.Object的)」方法,和這種方法不能被翻譯成表達商店

public tblOpportunity GetOpportunityByCode(string clientCode, string opportunityCode) 
     { 
      tblOpportunity opportunity = null; 

      ConnectionHandler.Invoke<EntityConnection>((connection) => 
      { 
       var context = new xxEntities(); 
       opportunity = context.tblOpportunities.FirstOrDefault<tblOpportunity>(o => o.ClientCode == clientCode && o.OpportunityCode == Convert.ToInt32(opportunityCode)); 
      }); 

      return opportunity; 
     } 
    } 

public partial class tblOpportunity 
    { 

     public int OpportunityCode { get; set; } 
+0

你嘗試過'o.OpportunityCode.ToString()== opportunityCode'嗎? – Mzf

+0

你確定它是int類型嗎?因爲它可以是int嗎? (可爲空)或者你可以使用automapper來映射輸出linq查詢到你的領域特定模型,這將減少手動映射的痛苦 – rajansoft1

+0

是的它是好的 –

回答

4
public tblOpportunity GetOpportunityByCode(string clientCode, string opportunityCode) 
    { 
     tblOpportunity opportunity = null; 
     var convertedOpportunityCode = Convert.ToInt32(opportunityCode); 
     ConnectionHandler.Invoke<EntityConnection>((connection) => 
     { 
      var context = new DMSEntities(); 
      opportunity = context.tblOpportunities.FirstOrDefault<tblOpportunity>(o => o.ClientCode == clientCode && o.OpportunityCode == convertedOpportunityCode); 
     }); 

     return opportunity; 
    } 

這應該做的伎倆。你的問題是,實體框架不能將你的表達式轉換爲有效的sql,因爲類似Convert.ToInt32的東西在sql中不存在。

1

可以很容易地通過首先執行轉換解決此然後查詢數據庫:

public tblOpportunity GetOpportunityByCode(
          string clientCode, string opportunityCode) 
{ 
    tblOpportunity opportunity = null; 

    var convertedOpportunityCode = Convert.ToInt32(opportunityCode); 

    ConnectionHandler.Invoke<EntityConnection>((connection) => 
    { 
     var context = new xxEntities(); 
     opportunity = context.tblOpportunities 
          .FirstOrDefault(o => 
           o.ClientCode == clientCode && 
           o.OpportunityCode == convertedOpportunityCode); 
    }); 

    return opportunity; 
} 
0

的方法不會因爲它不能直接轉換爲後備存儲查詢語言表達中的工作,但你在良好的範圍之前做您的轉換以及;先將字符串解析爲整數,然後在查詢中使用本地定義的int

這樣做,我個人可以使用int.TryParse而不是Convert.ToInt32,這樣你可以更合適地處理無效輸入,而不是隻是將結果扔到表達式中。

1

LINQ告訴你的是它沒有實現將ToInt32功能推到後端的功能。然而,你可以在你自己的代碼沒有問題:

public tblOpportunity GetOpportunityByCode(string clientCode, string opportunityCode) { 
    tblOpportunity opportunity = null; 
    // Do the conversion outside LINQ 
    var opCodeInt = Convert.ToInt32(opportunityCode); 
    ConnectionHandler.Invoke<EntityConnection>((connection) => { 
     var context = new xxEntities(); 
     opportunity = context.tblOpportunities.FirstOrDefault<tblOpportunity>(
      o => o.ClientCode == clientCode && o.OpportunityCode == opCodeInt 
     ); //              ^^^^^^^^^ 
    }); 
    return opportunity; 
} 
相關問題