Search code examples
c#entity-frameworkodataazure-mobile-services

Azure Mobile Services C#: how to return full inherited entity and not only the fields of the ancestor


I have few entities that inherit from a common ancestor.

public class Ancestor : EntityData {
 public string AncestorType { get; set; } //kind of enum
}

public class DescendantA : Ancestor {
 public string DescendantAProp { get; set; }
}

public class DescendantB : Ancestor {
 public int DescendantBProp { get; set; }
}

I created a controller AncestorController to retrieve all the entities in a single call, without the need to replicate the same call several time for DescendantA, DescendantB, etc.

The controller, scaffolded, looks like this:

public class AncestorController : TableController<Ancestor>
{
...

  public IQueryable<Ancestor> GetAllAncestor()
  {
    return Query(); 
  }

...
}

Unfortunately the method GetAllAncestor() returns only elements with the fields of Ancestor, and not the fields of DescendantA and/or DescendantB.

E.g. example of returned JSON:

[
    {
        "deleted": false,
        "updatedAt": "2018-01-23T00:05:52.3Z",
        "createdAt": "2018-01-23T00:05:52.3Z",
        "version": "AAAAAAAAB9Q=",
        "id": "07434aaa-c51a-425a-aca4-90bfb9a06a54",
        "ancestorType": "DescendantA"
    },
    {
        "deleted": false,
        "updatedAt": "2018-01-24T23:00:20.907Z",
        "createdAt": "2018-01-24T23:00:20.692Z",
        "version": "AAAAAAAAJ2U=",
        "id": "08f89ee7-ca78-46ea-9b6a-ef23bda3299b",
        "ancestorType": "DescendantB"
    }
]

while I would like to see:

[
    {
        "deleted": false,
        "updatedAt": "2018-01-23T00:05:52.3Z",
        "createdAt": "2018-01-23T00:05:52.3Z",
        "version": "AAAAAAAAB9Q=",
        "id": "07434aaa-c51a-425a-aca4-90bfb9a06a54",
        "ancestorType": "DescendantA",
        "DescendantAProp": "SomeValueA"
    },
    {
        "deleted": false,
        "updatedAt": "2018-01-24T23:00:20.907Z",
        "createdAt": "2018-01-24T23:00:20.692Z",
        "version": "AAAAAAAAJ2U=",
        "id": "08f89ee7-ca78-46ea-9b6a-ef23bda3299b",
        "ancestorType": "DescendantB",
        "DescendantBProp": "SomeValueB"
    }
]

What should I do to achieve such a goal?

Thanks!!!

cghersi


Solution

  • You can use view from SQL which gives you this Result

    Create View Combine AS BEGIN Select * from DescendantB UNION Select * from DescendantA END

    and Then in the Table Controller use View instead of table

    public class CombineController : TableController<Combine>
    {
     ...
    
      public IQueryable<Combine> GetAllAncestor()
      {
    return Query(); 
     }
    
    ... 
     }