实体框架4自我加入 - 延迟加载父对象和子集合

时间:2014-06-26 13:59:45

标签: c# entity-framework self-join

我正在尝试使用实体框架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

1 个答案:

答案 0 :(得分:0)

使用&#34;包括&#34;用于加载Collection的方法:

var selectedList = entity.where(m=>m.parent==null).include(m=>m.Categories).tolist();