在LINQ to Entities中连接int和string

Wah*_*eed 11 linq linq-to-entities entity-framework

我使用以下代码:

from c in Country
 where c.IsActive.Equals(true)
 orderby c.CountryName
 select new
 {
     countryIDCode = c.CountryID + "|" + c.TwoDigitCode,
     countryName = c.CountryName
 }
Run Code Online (Sandbox Code Playgroud)

但是我在运行它时遇到了这个错误:

无法将类型"System.Int32"强制转换为"System.Object"类型.LINQ to Entities仅支持转换实体数据模型基元类型.

CountryID是int类型,TwoDigitCode是string类型.

我如何正确连接?

小智 23

使用System.Data.Objects.SqlClient.SqlFunctions.StringConvert

 from c in Country
 where c.IsActive.Equals(true)
 orderby c.CountryName
 select new
 {
     countryIDCode = SqlFunctions.StringConvert((double)c.CountryID) 
                     + "|" + c.TwoDigitCode,
     countryName = c.CountryName
 }
Run Code Online (Sandbox Code Playgroud)


Nic*_*ray 7

如果此错误阻止您进行并且是一个小型数据集,则可以通过枚举查询(调用ToList)来保存从数据库中检索的内容.从那时起,您的操作将针对内存中的对象,您可能不会遇到您收到的错误.

var countries = (from c in Country
where c.IsActive.Equals(true)
orderby c.CountryName
select c).ToList();


var countryCodes = (from c in countries
where c.IsActive.Equals(true)
    orderby c.CountryName
    select new
    {
        countryIDCode = c.CountryID + "|" + c.TwoDigitCode,
        countryName = c.CountryName
    });
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案已经过时,总体上是不好的做法.这是一个快速的解决方案,现在可以使用但稍后会咬你(例如当你当前的小数据集突然增长,或者客户决定他想要在另一个更大的数据集上完全相同的东西).请参阅flyfisher1952的答案,该答案直接使用数据库函数,使其成为解决问题的一种比此答案更好的方法. (7认同)

gin*_*boy 5

本主题包含可以转换为命令树规范函数并在服务器上执行的CLR方法列表:

MSDN

对于不在此列表中的CLR方法,您必须使用.AsEnumerable()将结果下拉到客户端并执行LINQ to Objects查询.