当我执行以下代码时:
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 does not recognize the method 'System.Linq.IQueryable`1[DestKosher.Model.HotelModel] GetHotelsByCityId(Int32)' method, and this method cannot be translated into a store expression.
方法 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())
});
最佳答案
根据设计, 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
});
关于c# - LINQ to Entities 无法识别方法 'System.Linq.IQueryable` 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13487687/