【问题标题】:Entity Framework 4 Self Join - Lazy loading both Parent object and Child CollectionEntity Framework 4 Self Join - 延迟加载父对象和子集合
【发布时间】:2014-06-26 13:59:44
【问题描述】:

我正在尝试使用实体框架 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 外键引用父类别。使用这个工具,我可以使用Foreign Key 属性延迟加载ParentCategory。但是子集合Categories 并不是延迟加载。如何强制延迟加载子集合?

编辑

如果我没有过滤父子集合的结果集延迟加载将正常工作:

var cat = context.Category.ToList();

如果我过滤结果集,子集合将不会被延迟加载

var cat = from entity in context.Category
          where entity.Parent == null
          select entity;
//child collection will be null

【问题讨论】:

  • 你不能,它应该默认启用。检查您是否没有在代码上执行Include(...) 之类的操作。您还确定它不是延迟加载的吗?您是否真的看到向数据库触发了单个 SQL 查询?
  • 我的代码中没有使用任何包含。子集合在它应该具有值的地方总是 null
  • 问题更新!请看看并帮助我

标签: c# entity-framework self-join


【解决方案1】:

使用“包含”方法加载集合:

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

【讨论】:

  • 我想使用Include 方法使其延迟加载而不是急切加载。但是谢谢你的关注,anw
猜你喜欢
  • 1970-01-01
  • 2017-02-28
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 2023-04-05
相关资源
最近更新 更多