OData expand self referencing

Viewed 28

I'm trying to get Self-referencing to work with OData. Entities are always returned with a null parent even though the database contains Parent/Child references. When using the api instead of OData, the list comes up correctly with all references.

Example with a Test class which has a Test parent

OData Call: /odata/TestsOData?$expand=Parent

Expected JSON response

[
   {
      "Id": 1,
      "Name": "Test1",
      "Parent": null
   },
   {
      "Id": 2,
      "Name": "Test2",
      "Parent": {
         "Id": 1,
         "Name": "Test1",
         "Parent": null
      }
   }
]

Actual JSON response

[
   {
      "Id": 1,
      "Name": "Test1",
      "Parent": null
   },
   {
      "Id": 2,
      "Name": "Test2",
      "Parent": null
   }
]

CLASS

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }

    [ForeignKey("ParentId")]
    public virtual Test Parent { get; set; }

    public virtual ICollection<Test> ChildrenTests { get; set; }
}

EF configuration

modelBuilder
      .Entity<Test>()
      .HasOne(x => x.Parent)
      .WithMany(x => x.ChildrenTests)
      .HasForeignKey(x => x.ParentId);

DTO

public class TestDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public TestDto Parent { get; set; }
}

Controller

[HttpGet]
[EnableQuery]
public IActionResult Get()
{
    return Ok(_testManager.Get()); //Return a IQueryable<TestDto>
}

Startup.cs

private static IEdmModel GetEdmModel()
{
    var builder = new ODataConventionModelBuilder();

    builder.EntitySet<TestDto>("TestsOData");

    return builder.GetEdmModel();
}

Can anyone help?

Thanks

0 Answers
Related