OData客户端$ expand不起作用

时间:2015-07-28 09:08:46

标签: c# asp.net odata

使用的软件:

  • ASP.Net Web Api 2
  • OData v4
  • Microsoft OData Client 6.13

考虑以下模型:

  

位置(Id,LocationName,Street,PostalCodeId)

     

PostalCode(Id,ZIP)

位置有一个 PostalCode PostalCode 有许多位置

这是OData-Configuration:

ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Location>("Locations");
builder.EntitySet<PostalCode>("PostalCodes");

config.MapODataServiceRoute(
            routeName: "ODataRoute",
            routePrefix: "odata",
            model: builder.GetEdmModel());

模型类:

public class Location {
    [Key]
    public int Id { get; set; }
    public String LocationName { get; set; }
    public String Street { get; set; }
    public int PostalCodeId { get; set; }
    [ForeignKey("PostalCodeId")]
    public PostalCode PostalCode { get; set; }
}

public class PostalCode {
    public int Id { get; set; }
    public string ZIP { get; set; }
    public List<Location> Locations { get; set; }
}

在浏览器中调用http://localhost:49938/odata/Locations?$expand=PostalCode&$orderby=LocationName $ expand 有效:

{
  "@odata.context": "http://localhost:49938/odata/$metadata#Locations",
  "value": [
    {
      "Id": 1,
      "LocationName": "My Location 1",
      "Street": "Street 7",
      "PostalCodeId": 1838,
      "PostalCode": {
        "Id": 1838,
        "ZIP": "4081"
      }
    }
  ]
}

但是当我在应用程序中执行相同的请求时,它不起作用:

Container c = new Container(new Uri("http://localhost:49938/odata/"));
var result = c.Locations
                 .Expand(x => x.PostalCode)
                 .OrderBy(x => x.LocationName)
                 .ToList();

执行此代码时,PostalCodenull

1 个答案:

答案 0 :(得分:6)

Martinaut

new Container...var result= ...之间是否有任何查询操作?

如果是,请添加以下代码:

container.MergeOption = MergeOption.OverwriteChanges;

感谢。