我对 SQL Server、.NET 和 MVC 3/4 还很陌生,所以请多多包涵。我在 Linq-to-SQL 中创建了一个查询,该查询返回了我需要的数据,但不幸的是,我的主机提供程序不支持DbGeography
该类,特别是这里的DbGeography.PointFromText
方法Description。
所以我创建了一个存储过程,第一部分开始工作,但我很难总结和平均数据。我想返回SELECT
按 分组的语句中的所有数据Dish.DishId, Rest.RerstaurantId
,并为每个组添加rev.Rating
转换为和计数列。AVG(rev.Rating)
这是有效但不受支持的代码:
public static DbGeography CreatePoint(double latitude, double longitude)
{
var text = string.Format(CultureInfo.InvariantCulture.NumberFormat,
"POINT({0} {1})", longitude, latitude);
return DbGeography.PointFromText(text, 4326);
}
public static double MilesToMeters(double? miles)
{
if (miles == null)
return 0;
return miles.Value * 1609.344;
}
[HttpGet]
public JsonResult TopRated(double lat, double lng, double miles)
{
var source = CreatePoint(lat,lng);
var dist = MilesToMeters(miles);
var reviews = (from r in db.Reviews
where r.Restaurant.Location.Distance(source) <= dist
group r by new {
r.Dish,
r.Restaurant.Name,
r.Restaurant.Lat,
r.Restaurant.Lng
} into rg
select new {
Rating = rg.Average(r => r.Rating),
Count = rg.Count(),
Dish = rg.Key.Dish,
Restaurant = new {
Name = rg.Key.Name,
Lat = rg.Key.Lat,
Lng = rg.Key.Lng
}
});
reviews = reviews.OrderByDescending(r => r.Rating);
return Json(reviews, JsonRequestBehavior.AllowGet);
}
这里是需要修改的存储过程
CREATE PROCEDURE [dbo].[SearchNearbyReview]
@Lat decimal(9,6),
@Lng decimal(9,6),
@Dist decimal(9,6)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @pos geography;
SET @pos = geography::STPointFromText('POINT('
+ CONVERT(varchar(15), @Lng) + ' '
+ CONVERT(varchar(15), @Lat) + ')',
4326)
SELECT
rev.Rating,
rest.RestaurantId,
rest.Name AS RestaurantName,
rest.[Address],
rest.City,
rest.[State],
rest.Zip,
rest.Lat,
rest.Lng,
dish.DishId,
dish.Name AS DishName
FROM dbo.Reviews rev
INNER JOIN dbo.Restaurants rest
ON rev.Restaurant_RestaurantId = rest.RestaurantId
INNER JOIN dbo.Dishes dish
ON rev.Dish_DishId = dish.DishId
WHERE rest.Location.STDistance(@pos) <= (@Dist * 1609.334)
ORDER BY rest.RestaurantId, dish.DishId
END