0

当我尝试对下一个实体进行自我引用时

public class Folder
{
    public int Id { get; set; }
    public int?  ParentFolderId { get; set; } // Added property
    public string Name { get; set; }


    public virtual ICollection<Folder> Childrens { get; set; } // Added property
    public virtual ICollection<ArticleTitle> ArticleTitles { get; set; }

}


public class ArticleTitle
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int? FolderId { get; set; }
    public virtual Folder Folder { get; set; }
    public virtual Article Article { get; set; }
}

我添加了一些属性(注释为“添加的属性”)和这行代码:

  modelBuilder.Entity<Folder>()
 .HasMany(s => s.Childrens)
 .WithOptional()
 .HasForeignKey(s => s.ParentFolderId);

并得到这个例外:

序列不包含任何元素

不是正确的自引用吗?

4

1 回答 1

1

这就是您的代码的样子:

public class Folder
{
    public int Id { get; set; }
    [ForeignKey("ParentFolder")]
    public int?  ParentFolderId { get; set; }
    public virtual Folder ParentFolder { get; set; }
    public string Name { get; set; }


    public virtual ICollection<Folder> Childrens { get; set; }
    public virtual ICollection<ArticleTitle> ArticleTitles { get; set; }

}
...

我很高兴它有帮助。

于 2013-04-07T00:06:18.380 回答