我有一个标准的父/子EF模型,如下所示。
我正在通过WebApi将此作为REST API公开,并且当前在获取节点时,它将返回完整的父子层次结构。
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; }
}
我正在通过WebApi将此作为REST API公开,并且当前在获取节点时,它将返回完整的父子层次结构。
{
"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": []
}]
}]
}
然而我需要获取请求的对象和仅返回其直接子项,以便我的消费者可以在用户浏览数据时构建可视化表示。
更新:感谢大家的评论,看起来很好,去掉虚拟的部分后,我遇到了困难。由于我在异步方法中,所以查找操作返回了对象并且我丢失了上下文。
[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);
}
非常感谢您的帮助
dbContext.DataDictionaries.Include(x=>x.Children);
应该足够了,Include关键字是使其被急切加载的原因。我认为现在启用了延迟加载时,序列化器会遍历每个属性,导致对您的懒惰子集合进行枚举,从数据库中加载它们并导致同样的过程重复发生于每个子项,从而产生一个老生常谈的N+1选择问题。 - Red