[英]how to convert int to string in Linq to entities
我在字符串(varchar)中的Db列,我需要將它分配給一個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();
EF提供程序不知道如何將Convert.ToInt()
轉換為可以針對數據庫運行的SQL。 您可以將結果拉回來並使用linq對象進行轉換,而不是在服務器上進行轉換:
// 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();
你不能直接這樣做,你可以做的是聲明一個私有變量來處理你的“映射”值,並公開未映射的屬性......
[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();
}
}
試試這個:
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();
你為什么不為這樣的目的使用鑄造,這是實現這一目標的更有效方法。
只需將Convert.ToInt32(plan.cap_group_code)
替換為(int)plan.cap_group_code
請記住,字符串中應該有一個值並且是int,否則它將顯示Exception。 如果您不確定,那么您可以進一步擴展轉換以使用null coalesciting運算符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.