2011-09-13 264 views
4

我必须将srting值转换为Int,但似乎Linq对实体不支持这一点。将字符串转换为INT到LINQ to Entities?

对于下面的代码,我有geting er错误。 anyonw知道如何将字符串转换为int。

var query = (from p in dc.CustomerBranch 
        where p.ID == Convert.ToInt32(id)// here is the error. 
        select new Location() 
        {Name=p.BranchName,Address=p.Address, Postcode=p.Postcode,City=p.City,Telephone=p.Telephone}).First(); 
     return query; 

误差为:LINQ实体无法识别方法“的Int32 ToInt32(System.String)”, 和这种方法不能被翻译成表达商店。

回答

4

做转换外LINQ:

var idInt = Convert.ToInt32(id); 
var query = (from p in dc.CustomerBranch 
        where p.ID == idInt 
        select new Location() 
        {Name=p.BranchName,Address=p.Address, Postcode=p.Postcode,City=p.City,Telephone=p.Telephone}).First(); 
     return query; 
+0

是的,这肯定会工作:)。但我不知道在查询中必须有这样做的方法.. – kandroid

+1

它依赖于LINQ提供程序什么将在linq中工作,哪些不会(即,linq提供程序是否能够将表达式转换为卧底语言或不)EF提供者它不支持这个转换表达式。 – Ankur

+0

@kandroid我认为它不是很好在查询中,尽管你可能做'p.ID.ToString()== id' – Manatherin

-1

不,他们不会。这样想一想; ToString()和parse()都是对象的方法。由于linq-to-entities试图将你的linq表达式转换为sql,所以这些都不可用。 如果需要在查询中执行此操作,则可能需要在linq-to-entities [1]中可用的Cast。在ToString的情况下,你可以使用SqlFunctions.StringConvert()[2]。

  1. http://msdn.microsoft.com/en-us/library/bb301460.aspx
  2. http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx
+3

-1。 Cast将提供的集合的元素转换为指定的类型。如果您向Cast提供字符串,它将尝试将该字符串转换为请求类型的IEnumerable。 –

相关问题