0

我想使用服务器分页的 OData 结果。

这意味着,JSON 代码包含一个元素

"__next": "http://server/odata.svc/table?$skiptoken=guid'4dda1cd9-7eff-423f-a314-08edf26a22e8'"

如何在 ASP.NET MVC 中执行此操作?我看到很多使用 OData 的示例,但没有一个处理分页数据。

我对 OData 和 MVC 都很陌生,所以请在答案中尽可能明显。;-)

4

2 回答 2

1

在 .NET 中使用 OData 的主要方式是使用 WCF 数据服务客户端库。在 Visual Studio 中,您可以右键单击一个项目,然后选择“添加服务引用”以开始使用。“添加服务引用”在后台使用 WCF 数据服务客户端库。有关如何使用客户端库的一般信息,请在此处查看 MSDN 文档:http: //msdn.microsoft.com/en-us/library/cc668772.aspx

不过需要注意的是:您发布的 JSON(带有"__next")是旧的 OData JSON 格式,有时称为“详细 JSON”。WCF 数据服务客户端不支持这种格式。它只支持 Atom 和新的 JSON 格式。只要您的服务器能够支持 Atom 或新的 v3 JSON,这对您来说应该不是问题。

至于您的实际问题,您可以在对象上使用该.GetContinuation()方法。QueryOperationResponse例如:

// "DemoService" is the auto-generated subclass of DataServiceContext created when you run "Add Service Reference"
DemoService context = new DemoService(new Uri(<url to the service root>));
var firstPage = context.Customers.Execute() as QueryOperationResponse<Customer>;
var token = firstPage.GetContinuation();
if (token != null)
    var secondPage = context.Execute<Customer>(token);

显然,您可能希望将其变成一个循环,但这应该让您对 API 的使用有一个基本的了解。有关详细信息,请参阅 MSDN 上的此页面:http: //msdn.microsoft.com/en-us/library/ee358711.aspx

于 2013-06-13T17:49:22.843 回答
0

如果您使用 MVC 和 OData,我强烈建议您使用 Web API 来执行此操作,而不要弄乱 WCF 的所有 WCF 配置复杂性。这是您的控制器希望使用 MVC Web API 实现的功能:(非常简单和干净)。

public class ProductController : EntitySetController<Product, int>
{
    private readonly IUnitOfWork _unitOfWork;

    public ProductController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public override IQueryable<Product> Get()
    {
        return _unitOfWork.Repository<Product>().Query().Get();
    }

    protected override Product GetEntityByKey(int key)
    {
        return _unitOfWork.Repository<Product>().FindById(key);
    }

    protected override Product UpdateEntity(int key, Product update)
    {
        update.State = ObjectState.Modified;
        _unitOfWork.Repository<Product>().Update(update);
        _unitOfWork.Save();
        return update;
    }

    public override void Delete([FromODataUri] int key)
    {
        _unitOfWork.Repository<Product>().Delete(key);
        _unitOfWork.Save();
    }

    protected override void Dispose(bool disposing)
    {
        _unitOfWork.Dispose();
        base.Dispose(disposing);
    }
}

你看这篇文章,完整的演练 http://blog.longle.net/2013/06/18/mvc-4-web-api-odata-entity-framework-kendo-ui-grid-datasource-with-虚拟机

于 2013-08-02T21:53:28.510 回答