当我尝试使用下一个实体进行自引用时
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);
得到这个例外:
序列不包含任何元素
自我引用不正确吗?
答案 0 :(得分: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; }
}
...
我很高兴它有所帮助。