fra*_*llo 54 rest odata asp.net-mvc-4 asp.net-web-api
我必须使用Web服务取得的WebAPI由ASP .NET MVC提供4.我知道其中的WebAPI自动工作在顶部层处理的OData查询(例如$filter
,$top
,$skip
),但如果我想自己处理过滤?
我不是简单地从我的数据库返回数据,但我有另一个层添加了一些属性,进行了一些转换等等.因此查询我的所有数据,转换它们并将它们返回到WebAPI类进行OData过滤不仅仅是好的足够.它当然非常慢,通常是一个糟糕的想法.
那么有没有办法将OData查询参数从我的WebAPI入口点传播到我调用的函数来获取和转换数据?
例如,/api/people?$skip=10&$top=10
要调用服务器的GET :
public IQueryable<Person> get() {
return PersonService.get(SomethingAboutCurrentRequest.CurrentOData);
}
Run Code Online (Sandbox Code Playgroud)
并在PersonService
:
public IQueryable<Person> getPeople(var ODataQueries) {
IQueryable<ServerSidePerson> serverPeople = from p in dbContext.ServerSidePerson select p;
// Make the OData queries
// Skip
serverPeople = serverPeople.Skip(ODataQueries.Skip);
// Take
serverPeople = serverPeople.Take(ODataQueries.Take);
// And so on
// ...
// Then, convert them
IQueryable<Person> people = Converter.convertPersonList(serverPeople);
return people;
}
Run Code Online (Sandbox Code Playgroud)
quj*_*jck 41
我只是偶然发现了这个老帖子,我正在添加这个答案,因为现在很容易自己处理OData查询.这是一个例子:
[HttpGet]
[ActionName("Example")]
public IEnumerable<Poco> GetExample(ODataQueryOptions<Poco> queryOptions)
{
var data = new Poco[] {
new Poco() { id = 1, name = "one", type = "a" },
new Poco() { id = 2, name = "two", type = "b" },
new Poco() { id = 3, name = "three", type = "c" }
};
var t = new ODataValidationSettings() { MaxTop = 2 };
queryOptions.Validate(t);
//this is the method to filter using the OData framework
//var s = new ODataQuerySettings() { PageSize = 1 };
//var results = queryOptions.ApplyTo(data.AsQueryable(), s) as IEnumerable<Poco>;
//or DIY
var results = data;
if (queryOptions.Skip != null)
results = results.Skip(queryOptions.Skip.Value);
if (queryOptions.Top != null)
results = results.Take(queryOptions.Top.Value);
return results;
}
public class Poco
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21874 次 |
最近记录: |