Entity Framework Parent Child Table return immediate children only

Viewed 3207

I have a standard Parent / Child EF model as below

public class DataDictionary 
{
    public int Id { get; set; }
    public String Name { get; set; }

    public int? ParentId { get; set; }

    [JsonIgnore]
    public virtual DataDictionary Parent { get; set; }

    public virtual ICollection<DataDictionary> Children { get; set; }
}

I am exposing this as a REST api via WebApi and currently it will return the complete parent child hierarchy when I GET a node as below.

{
"Id": 1,
"Name": "root",
"SegmentKey": null,
"ParentId": null,
"Children": [{
    "Id": 2,
    "Name": "Demographics",
    "SegmentKey": null,
    "ParentId": 1,
    "Children": [{
        "Id": 3,
        "Name": "Gender",
        "ParentId": 2,
        "Children": []
    }, {
        "Id": 4,
        "Name": "Age",
        "ParentId": 2,
        "Children": []
    }, {
        "Id": 5,
        "Name": "Income",
        "ParentId": 2,
        "Children": []
    }]
}, {
    "Id": 6,
    "Name": "Activity",
    "SegmentKey": null,
    "ParentId": 1,
    "Children": [{
        "Id": 7,
        "Name": "Navigation",
        "SegmentKey": null,
        "ParentId": 6,
        "Children": []
    }, {
        "Id": 8,
        "Name": "Behaviour",
        "SegmentKey": null,
        "ParentId": 6,
        "Children": []
    }]
}]
}

However I need to get the requested object and the immediate children only to be returned only so that my consumers can build up the visual representation as the user navigates through the data.

UPDATE: Thanks for the comments guys, all looks good taking off the virtual however am struggling with the .Include as I am in an async method where the find returns the object and I have lost the context. i.e.

    [ResponseType(typeof(DataDictionary))]
    public async Task<IHttpActionResult> GetDataDictionary(int id)
    {
        DataDictionary dataDictionary = await db.DataDictionaries.FindAsync(id);
        if (dataDictionary == null)
        {
            return NotFound();
        }
        return Ok(dataDictionary);
    }

Any help would be gratefully received

2 Answers
Related