Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 未在自引用关系中加载导航属性_C#_Entity Framework - Fatal编程技术网

C# 未在自引用关系中加载导航属性

C# 未在自引用关系中加载导航属性,c#,entity-framework,C#,Entity Framework,我有一个具有自引用关系的模型类别: public class Category { public Category() { this.Childs = new HashSet<Category>(); } public int CategoryId { get; set; } public int? ParentId { get; set; } public virtual Category Parent { get

我有一个具有自引用关系的模型
类别

public class Category
{
    public Category()
    {
        this.Childs = new HashSet<Category>();
    }

    public int CategoryId { get; set; }

    public int? ParentId { get; set; }
    public virtual Category Parent { get; set; }

    public HashSet<Category> Childs { get; set; }

    //... other useless properties
}
现在发生了非常奇怪的行为。我称之为方法:

var categoriesEntites =
        this.catogries.AsQuerable()
                      .Where(cat => cat.ProjectId == projectId 
                                    && cat.ParentId == null)
                      .ToList();
// this.categories is of type `Repository<Category>`
突然,导航属性开始工作。。

我以前使用过很多次这样的方法,我从来没有遇到过这样的问题。。 一些想法<代码>懒散加载
当然是打开的

更奇怪的是,我有另一个自引用实体(以完全相同的方式构建),并且没有这样的bug

顺便说一句。对于nav属性中的键入错误,很抱歉,它应该是
Childs
,当然不是
Childs

当您在
GetAll()
方法中执行
ToList()
时,EF将加载整个表并在本地存储这些实体。这就是执行此查询时它们显示为已加载的原因:

var categoriesEntites =
    this.catogries.AsQuerable()
                  .Where(cat => cat.ParentId == null)
                  .ToList();
如果查看为上述查询生成的SQL,它实际上只获取
ParentId
为空的类别:

SELECT 
    [Extent1].[CategoryId] AS [CategoryId], 
    [Extent1].[ParentId] AS [ParentId]
    FROM [dbo].[Categories] AS [Extent1]
    WHERE [Extent1].[ParentId] IS NULL
即使在VS debugger中检查了集合(触发延迟加载),也不会获取子集合,因为EF已在本地加载并存储了它

如果要在不使用
ToList()
(或
GetAll()
)的情况下获取子对象,请在子集合上使用
virtual
关键字。这是延迟加载的要求,当代码或VS调试器访问该子集合时,将获取该子集合

public virtual HashSet<Category> Childs { get; set; }
公共虚拟哈希集Childs{get;set;}
var categoriesEntites =
    this.catogries.AsQuerable()
                  .Where(cat => cat.ParentId == null)
                  .ToList();
SELECT 
    [Extent1].[CategoryId] AS [CategoryId], 
    [Extent1].[ParentId] AS [ParentId]
    FROM [dbo].[Categories] AS [Extent1]
    WHERE [Extent1].[ParentId] IS NULL
public virtual HashSet<Category> Childs { get; set; }