2

当我执行以下代码时:

IHotelDataAccess _hotelDataAccess= new HotelDataAccess(_entities);
int myVal = (from u in _hotelDataAccess.GetHotelsByCityId(19)
    select u).Count();

myVal 按预期返回一个整数值,但是如果我尝试返回 IQueryable 如下

return (from geoLocation in _entities.ViewGeographyLocation
 where geoLocation.CountryCode == countryCode
 orderby geoLocation.SortOrder, geoLocation.CityName
 select new ContinentModel
 {
  ContinentCode = geoLocation.ContinentCode,
  ContinentName = geoLocation.ContinentName,
  CountryCode = geoLocation.CountryCode,
  CountryName = geoLocation.CountryName,
  CityId = geoLocation.CityId,
  CityName = geoLocation.CityName,
  CityCode = geoLocation.CityName,
  TotalCount = ((from u in _hotelDataAccess.GetHotelsByCityId(19)
   select u).Count())
 });

我得到错误:

LINQ to Entities 无法识别方法 'System.Linq.IQueryable`1[DestKosher.Model.HotelModel] GetHotelsByCityId(Int32)' 方法,并且此方法无法转换为商店表达式。

方法 hotelDataAccess.GetHotelsByCityId(19) 返回 IQueryable。任何想法、帮助或解决方案将不胜感激。问候,

马丁

更新:

最初设置此查询是为了查看通过将整数放入函数 GetHotelsByCityId 是否有效。但是,我最终想做的是:

return (from geoLocation in _entities.ViewGeographyLocation
 where geoLocation.CountryCode == countryCode
 orderby geoLocation.SortOrder, geoLocation.CityName
 select new ContinentModel
 {
  ContinentCode = geoLocation.ContinentCode,
  ContinentName = geoLocation.ContinentName,
  CountryCode = geoLocation.CountryCode,
  CountryName = geoLocation.CountryName,
  CityId = geoLocation.CityId,
  CityName = geoLocation.CityName,
  CityCode = geoLocation.CityName,
  TotalCount = ((from u in _hotelDataAccess.GetHotelsByCityId(geoLocation.CityId)
   select u).Count())
 });
4

2 回答 2

3

按照设计,LINQ to Entities需要将整个 LINQ 查询表达式转换为服务器查询。在翻译查询之前,只有少数不相关的子表达式(查询中不依赖于服务器结果的表达式)在客户端上进行评估。不支持没有已知转换的任意方法调用,例如本例中的 GetHotelsByCityId()。

你可以这样做

var list = _hotelDataAccess.GetHotelsByCityId(19).ToList();
int myVal = (from u in list
    select u).Count();

在您的查询中比我们 myval

return (from geoLocation in _entities.ViewGeographyLocation
 where geoLocation.CountryCode == countryCode
 orderby geoLocation.SortOrder, geoLocation.CityName
 select new ContinentModel
 {
  ContinentCode = geoLocation.ContinentCode,
  ContinentName = geoLocation.ContinentName,
  CountryCode = geoLocation.CountryCode,
  CountryName = geoLocation.CountryName,
  CityId = geoLocation.CityId,
  CityName = geoLocation.CityName,
  CityCode = geoLocation.CityName,
  TotalCount = myVal 
 });

阅读更多详情:LINQ to Entities,什么不受支持?

于 2012-11-21T06:39:29.923 回答
0

尝试添加命名空间“System.Linq”,如果您有“System.Core”程序集引用,还要检查您的项目引用。

于 2012-11-21T06:40:52.320 回答