2011-11-17 107 views
3

我的Db列中的字符串(varchar),我需要將它分配給一個int值。 我正在使用linq進行查詢。儘管代碼編譯在運行時收到錯誤。 在此先感謝。如何將int轉換爲Linq中的字符串到實體

PFB我的查詢:

var vlauesCap = from plan in entities.PA_RTM_CAP_Group 
       select new Business.PartnerProfile.LookUp 
       { 
       Id =Convert.ToInt32(plan.cap_group_code), 
       //(Int32)plan.cap_group_code, 
       Value = plan.cap_group_name 
         }; 
        return vlauesCap.ToList(); 
+0

你試過,如果它與'int.Parse'而不是'Convert.ToInt32'? –

+1

什麼是錯誤? cap_group_code的實際類型和價值是什麼? –

回答

7

EF提供程序不知道如何將Convert.ToInt()轉換爲可以針對數據庫運行的SQL。而不是做在服務器上的轉換,你可以拉的結果反饋和使用LINQ to對象進行轉換:

// the ToList() here causes the query to be executed on the server and 
// the results are returned in a list of anonymous objects 
var results = (from plan in entities.PA_RTM_CAP_Group 
       select new 
       { 
        Code = plan.cap_group_code, 
        Name = plan.cap_group_name 
       }).ToList(); 

// the conversion can now be done here using Linq to Objects 
var vlauesCap = from r in results 
       select new Business.PartnerProfile.LookUp 
       { 
        Id = Convert.ToInt32(r.Code), 
        Value = r.Name 
       }; 

return vlauesCap.ToList(); 
+0

或者只是在entities.PA_RTM_CAP_Group上調用AsEnumerable():) – Polity

+0

@Polity,是的,但是這樣你只需要傳輸你需要的2列。 –

0

試試這個:

var vlauesCap = from plan in entities.PA_RTM_CAP_Group 
            select new Business.PartnerProfile.LookUp 
            { 
             Id =Convert.ToInt32(plan.cap_group_code), 
             Convert.ToInt32(plan.cap_group_code), 
             Value = plan.cap_group_name 

            }; 
        return vlauesCap.ToList(); 
-2

你爲什麼不使用鑄造這樣的目的,就是實現這一目標的一個更有效的方法。

只是(int)plan.cap_group_code

更換Convert.ToInt32(plan.cap_group_code)千萬記住,應該有一個字符串的值,並詮釋,否則它會顯示異常。如果您不確定,那麼您可以進一步擴展鑄造以使用null coalesciting運算符

1

你不能直接這樣做,你能做的就是聲明一個私有變量來處理你的「映射」的價值,並揭露未映射的財產...

[Column(Name = "cap_group_code", Storage = "m_cap_group_code")] 
private string m_cap_group_code; 

public int cap_group_code { 
    get 
    { 
     return Int32.Parse(m_cap_group_code); 
    } 
    set 
    { 
     m_cap_group_code = value.ToString(); 
    } 
} 
相關問題