LINQ to Entities无法识别方法'System.Linq.IQueryable`1

时间:2012-11-21 06:37:28

标签: c# sql linq

当我执行以下代码时:

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())
 });

2 个答案:

答案 0 :(得分: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 
 });

继续阅读Deatil:LINQ to Entities, what is not supported?

答案 1 :(得分:0)

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