C# 实体框架4自连接-延迟加载父对象和子集合
我正在尝试使用entity framework 4实现自连接,我的用例如下:C# 实体框架4自连接-延迟加载父对象和子集合,c#,entity-framework,self-join,C#,Entity Framework,Self Join,我正在尝试使用entity framework 4实现自连接,我的用例如下: public class Category { /// <summary> /// category id /// </summary> [Key] [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] p
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; }
}
Buf如果我筛选结果集,则不会延迟加载子集合
var cat = from entity in context.Category
where entity.Parent == null
select entity;
//child collection will be null
使用Include方法加载集合:
var selectedList = entity.where(m=>m.parent==null).include(m=>m.Categories).tolist();
不能,默认情况下应该启用它。检查你没有做像包括。。。在你的代码上。另外,您确定它不是延迟加载的吗?你真的看到一个SQL查询被激发到数据库中了吗?我的代码中没有使用任何include。子集合应具有valueQuestion update的位置始终为空!请看一看,并帮助meI使用Include方法使其成为延迟加载而不是急切加载。但是谢谢你的关注,安
var selectedList = entity.where(m=>m.parent==null).include(m=>m.Categories).tolist();