我有一个从ApiController派生的WebApi控制器,它有一个服务操作:
public class Airports2Controller : ApiController
{
protected airportEntities db = new airportEntities ();
[Queryable]
[HttpGet]
public IQueryable<Airport> GetAirportsWithinRadius(int airportId, int radius)
{
//var radius = (int)parameters["radius"];
//var airportId = (int)parameters["airportId"];
var resultAirports = GetAirportsWithinRadius2(airportId, radius);
return resultAirports;
}
private IQueryable<Airport> GetAirportsWithinRadius2(int airportId, int radius)
{
var airports = db.Airports.SqlQuery("select * from Airport a where (select GeoLocation from airport where Id = @p0).STDistance(a.GeoLocation)/1.852/1000.00 < @p1", airportId, radius);
var airportIds = airports.Select(a => a.Id);
var resultAirports = db.Airports.Where(a => airportIds.Contains(a.Id));
return resultAirports;
}
}
我还为机场实体提供odata服务。由于.net webapi odata还没有支持odata函数(服务操作?),我需要创建一个辅助控制器(它不是从ODataController派生的)。
我现在想用jaydata做的是扩展上下文,除了odata之外还有服务操作,一旦db在initService中初始化:
$data.initService("http://localhost:2663/odata");
service.then(function (db) {
//now here manually extend the definition of the context to include the GetAirportsWithinRadius service operation.
});
}
这个控制器可以很好地使用get参数,并在从fiddler手动调用时返回正确的json。如何扩展jaydata上下文以获得GetAirportsWithinRadius(airportId,radius)方法?它的url需要手动设置,其类型需要更改为GET。此外,该方法是否可以与odata params组合,因为它是用[Queryable]声明的。在fiddler中手动调用时,它的一部分再次起作用。例如:
http://localhost:2663/api/Airports2/GetAirportsWithinRadius?airportId=2112&radius=50&?$inlinecount=allpages&$top=2
这很好地返回了两个机场实体对象......
由于
答案 0 :(得分:1)
谢谢@robesz - 在.net中创建参数化的odata动作有一些微妙之处,这就是困扰我的事情(我在尝试行动之前无法让它发挥作用),但这次我得到了它:
[Queryable]
[HttpPost]
public IQueryable<Airport> GetAirportsWithinRadius([FromBody] ODataActionParameters parameters)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var radius = (int)parameters["radius"];
var airportId = (int)parameters["airportId"];
var resultAirports = GetAirportsWithinRadius2(airportId, radius);
return resultAirports;
}
ActionConfiguration getAirportsWithinRadius = modelBuilder.Entity<Airport>().Collection.Action("GetAirportsWithinRadius");
getAirportsWithinRadius.Parameter<int>("airportId");
getAirportsWithinRadius.Parameter<int>("radius");
getAirportsWithinRadius.ReturnsCollectionFromEntitySet<Airport>("Airports");
有了这个,我现在可以使用jaydata执行以下操作:
var service = $data.initService("http://localhost:2663/odata");
return service.then(function (db) {
airports = db.Airports.GetAirportsWithinRadius(2112,50);
airports.filter("it.Abbrev== a", {a: 'C44'}).forEach(function(a){console.log(a.Abbrev)});
});
我快乐地跳来跳去:)