OData按导航属性排序

时间:2014-03-22 05:56:40

标签: c# asp.net linq-to-entities odata wcf-data-services

我试图在ASP.NET MVC项目中使用Northwind OData服务并使用WebGrid控件进行虚拟化。我使用服务URL使用Visual Studio 2012创建服务引用。问题在于WebGrid的排序。当我尝试在导航字段上对它进行排序时,比如CategoryName,我收到一个错误:"没有属性或字段' CategoryName'存在于'产品'"中。我理解错误,但我不知道如何完成这项工作并获得所需的数据部分。任何帮助将不胜感激。 控制器:

private ODataNorthwind.NorthwindEntities context = new ODataNorthwind.NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc"));
    //
    // GET: /Odata/

    public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sort = "ProductID", string sortDir = "ASC")
    {
        var data = GetProducts(page, rowsPerPage, sort, sortDir);
        return View(data);
    }

    // Data for WebGridObj
    private WebGridViewModel GetProducts(int page = 1, int rowsPerPage = 10, string sort = "ProductID", string sortDir = "ASC")
    {
        var query = context.Products.OrderBy(sort + " " + sortDir)
            .Select(p => new
            {
                p.ProductID,
                p.ProductName,
                p.Category.CategoryName,
                p.Supplier.CompanyName,
                p.Supplier.Country
            });

        WebGridViewModel model = new WebGridViewModel
        {
            TotalRows = query.Count(),
            Products = query.Skip((page - 1) * rowsPerPage).Take(rowsPerPage).ToList().Select(p =>
               new HtmlViewModel
               {
                   ProductId = p.ProductID,
                   ProductName = p.ProductName,
                   CategoryName = p.CategoryName,
                   CompanyName = p.CompanyName,
                   Country = p.Country
               })
        };
        return model;
    }

查看:

@{
    ViewBag.Title = "WebGrid";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>OData WebGrid</h2>

<div>
@{
    var grid = new WebGrid(null, defaultSort: "ProductId");
    grid.Bind(Model.Products, rowCount: Model.TotalRows, autoSortAndPage: false);
}
@grid.GetHtml(columns: grid.Columns(
    grid.Column("ProductId"),
    grid.Column("ProductName"),
    grid.Column("CategoryName"),
    grid.Column("CompanyName"),
    grid.Column("Country")
    ))
</div>

1 个答案:

答案 0 :(得分:1)

调用GetProducts时,将Category/CategoryName而不是CategoryName作为参数的排序值可以解决此问题。

http://services.odata.org/Northwind/Northwind.svc/Products?
     $expand=Category&$orderby=Category/CategoryName