2011-11-17 80 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(); 
    } 
}