我正在尝试使用实体框架4实现自联接,我的用例如下:
public class Category
{
/// <summary>
/// category id
/// </summary>
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int CatID { get; set; }
/// <summary>
/// category name
/// </summary>
[Required(ErrorMessage="Vui lòng nhập tên.")]
[MaxLength(100, ErrorMessage="Tên chỉ có độ dài tối đa 100 ký tự.")]
public string CatName { get; set; }
/// <summary>
/// parent category id
/// self join :)
/// </summary>
public int? ParentID { get; set; }
/// <summary>
/// parent category
/// </summary>
[ForeignKey("ParentID")]
public virtual Category ParentCategory { get; set; }
/// <summary>
/// products list
/// </summary>
public virtual IEnumerable<Product> Products { get; set; }
/// <summary>
/// categories which are associate with this category
/// </summary>
public virtual IEnumerable<Category> Categories { get; set; }
}
如您所见,子类别将通过ParentID
外键引用父类别。通过此工具,我可以使用ParentCategory
属性延迟加载Foreign Key
。但是子集合Categories
并没有延迟加载。如何强制延迟加载子集合?
修改
如果我没有过滤结果集,父和子集合的延迟加载将正常工作:
var cat = context.Category.ToList();
Buf如果我过滤结果集,子集合将不会延迟加载
var cat = from entity in context.Category
where entity.Parent == null
select entity;
//child collection will be null
答案 0 :(得分:0)
使用&#34;包括&#34;用于加载Collection的方法:
var selectedList = entity.where(m=>m.parent==null).include(m=>m.Categories).tolist();