如何从odata服务返回嵌套实体模型

时间:2014-01-07 14:26:31

标签: c# asp.net-web-api odata

我实施了ODataServiceSample

它说,您可以查询嵌套实体模型,如

public class ProductFamily
{
    public ProductFamily()
    {
        Products = new List<Product>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual Supplier Supplier { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

但您可以查询主要类别的部分首次请求

Container ctx = new Container();
foreach (var productFamily in ctx.ProductFamilies)
    Console.WriteLine("\t{0}-{1}: {2}", productFamily.ID, productFamily.Name, productFamily.Description);

第二次子类请求

private static void Get_ProductFamily_Products()
    {
        Container ctx = new Container();
        var query = ctx.ProductFamilies.Where(p => p.ID == 3).SelectMany(p => p.Products);
        foreach (var product in query)
            Console.WriteLine("\t{0}-{1}", product.ID, product.Name);
    }

如何在一个查询(请求)中选择所有数据?

1 个答案:

答案 0 :(得分:0)

要展开相关实体,请在查询中添加Expand。在你的情况下,它可能是这样的:

Container ctx = new Container();
foreach (var productFamily in ctx.ProductFamilies.Expand("Products"))
{
    Console.WriteLine("\t{0}-{1}: {2}", 
        productFamily.ID, productFamily.Name, productFamily.Description);
    foreach (var product in productFamily.Products)
    {
        Console.WriteLine("\t\t{0}-{1}", 
            product.ID, product.Name);
    }
}