首先,我有一个函数,它有两个参数(经度,纬度)。
RETURNS TABLE
AS
RETURN
(
select dbo.GeoCalculateDistance (@lat1Degrees,@lon1Degrees,Latitude,Longitude) as Distance, PKRestaurantId as PkKeyId from StRestaurant
)
如你所知,我有一张桌子叫餐厅。在这个表中,我有4列(PkRestaurantId, RegionId, Longitude, Latitude)。
并且,我需要一个接受4个参数的方法
public List<RestaurantDetailDto> GetRestaurant(int regionid, decimal latitude, decimal longitude, OrderType orderType)
{}
这个方法会给我周围的餐馆。但是如果我想用距离系统化这个列表,我必须将我的Restaurant table和函数连接起来。这是我的查询。
var query = from restaurant in context.StRestaurant
join distance in context.CalculateDistanceTable(latitude, longitude) on restaurant.PKRestaurantId equals distance.PkKeyId
where restaurant.FKRegionId == regionid
select new
{
Restaurant = restaurant,
DistanceTable = distance,
};
然后检查orderType
switch (orderType)
{
case OrderType.Distance:
query = query.OrderBy(x => x.DistanceTable.Distance);
break;
// and the anothers
}
最后,我试着把这个列表作为;
var queryResult = query.ToList();
我一直在犯这个错误:
嵌套查询没有合适的键
我也尝试了上面的查询,但它返回相同的错误:s
var query = context.StRestaurant.Where(x => x.FKRegionId == regionid && x.IsActive).Join(
context.CalculateDistanceTable(latitude, longitude),
restaurant => restaurant.PKRestaurantId,
result => result.PkKeyId,
(restaurant, result) => new
{
Restaurant = restaurant,
MinumumPackagePrice = restaurant.StRestaurantRegionRelation.FirstOrDefault(x => x.FKRestaurantId == restaurant.PKRestaurantId).MinumumPackageCharge,
DistanceTable = result,
RestaurantImage = restaurant.StRestaurantImage.Where(x => x.IsDefault && x.FKRestaurantId == restaurant.PKRestaurantId),
}
);
请帮助! !
我以前在对结果执行. include()时看到过这种情况。我想象你的投影(在第二个例子中)可能在内部做这个。你能把这个加到第一部分吗?
在本例中,我必须在源表上添加.Include()
:
from a in context.A.Include("relationship")
join b in context.MyFunction(...)
...
您可以在这里尝试一些事情。首先,重写SQL函数,使它有一个主键:
CREATE FUNCTION CalculateDistanceTable
(
-- Add the parameters for the function here
@lat1Degrees float,
@lon1Degrees float
)
RETURNS
@RestaurantDistances TABLE
(
-- Add the column definitions for the TABLE variable here
PkKeyId int NOT NULL primary key,
Distance float NOT NULL
)
AS
BEGIN
INSERT INTO @RestaurantDistances
SELECT dbo.GeoCalculateDistance(@lat1Degrees, @lon1Degrees, Latitude, Longitude) AS Distance, PKRestaurantId AS PkKeyId
FROM StRestaurant
RETURN
END
GO
同样,你可以尝试改变你的LINQ连接,使用匿名类型来执行连接。
var query = from restaurant in context.StRestaurant
join distance in context.CalculateDistanceTable(latitude, longitude) on new { Key = restaurant.PKRestaurantId } equals new { Key = distance.PkKeyId }
where restaurant.FKRegionId == regionid
select new
{
Restaurant = restaurant,
DistanceTable = distance,
};
如果这些都没有帮助,请告诉我,我会尽量在适当的时候更新这个答案。