OData client $expand does not work

坚强是说给别人听的谎言 提交于 2021-01-27 09:34:05

问题


Software used:

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

Consider the following Model:

Location (Id, LocationName, Street, PostalCodeId)

PostalCode (Id, ZIP)

A Location has one PostalCode and a PostalCode has many Locations.

This is the OData-Configuration:

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

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

Model classes:

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; }
}

When calling http://localhost:49938/odata/Locations?$expand=PostalCode&$orderby=LocationName in a browser $expand works:

{
  "@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"
      }
    }
  ]
}

But when I do the same request in the application, it does not work:

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

When I execute this code PostalCode is null.


回答1:


Martinaut

Is there any query operation between new Container... and var result= ...?

If yes, please add the following codes:

container.MergeOption = MergeOption.OverwriteChanges;

Thanks.



来源:https://stackoverflow.com/questions/31671927/odata-client-expand-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!