Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OData client $expand does not work

Tags:

c#

asp.net

odata

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.

like image 536
Martinaut Avatar asked Feb 10 '23 11:02

Martinaut


1 Answers

Martinaut

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

If yes, please add the following codes:

container.MergeOption = MergeOption.OverwriteChanges;

Thanks.

like image 144
Sam Xu Avatar answered Feb 11 '23 23:02

Sam Xu