我需要从 Web Api ODATA 控制器返回以下复杂类型:
public class TreeItem
{
public int Id { get; set; }
public string Name { get; set; }
public List<TreeItem> Children { get; set; }
}
这是控制器方法:
// GET: odata/TreeItems
public IHttpActionResult GetTreeItems(ODataQueryOptions<TreeItem> queryOptions)
{
// validate the query.
try
{
queryOptions.Validate(_validationSettings);
}
catch (ODataException ex)
{
return BadRequest(ex.Message);
}
var treeItems = new List<TreeItem>();
treeItems.Add(new TreeItem() { Id = 1, Name = "Geleiding", Children = new List<TreeItem>() { new TreeItem(){ Id=4, Name="Item1-1", Children=new List<TreeItem>()} } });
treeItems.Add(new TreeItem() { Id = 2, Name = "Item 2", Children = new List<TreeItem>() });
treeItems.Add(new TreeItem() { Id = 3, Name = "Item 3", Children = new List<TreeItem>() });
return Ok<IEnumerable<TreeItem>>(treeItems);
}
在WebApiConfig中: builder.EntitySet("TreeItems").EntityType.ComplexProperty(c => c.Children);
当我访问这个URL时:http://localhost:50997/odata/TreeItems 我会得到以下响应:
{
"odata.metadata":"http://localhost:50997/odata/$metadata#TreeItems","value":[
{
"Children":{
"Capacity":4
},"Id":1,"Name":"Geleiding"
},{
"Children":{
"Capacity":0
},"Id":2,"Name":"Item 2"
},{
"Children":{
"Capacity":0
},"Id":3,"Name":"Item 3"
}
]
}
如何获取包括所有可能级别的 Children 列表? $expand=Children 不起作用,提示 Children 不是一个导航属性。
感谢您的帮助!