Sequence contains no elements : self referencing code first

半城伤御伤魂 提交于 2019-12-25 00:37:01

问题


when I try to do self referencing with next entities

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; }
}

I added few properties (commented 'added property') and this line of code:

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

And get this exception:

Sequence contains no elements

Is it not correct self referencing?


回答1:


This is how your code should look like:

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; }

}
...

I'm glad it helped.



来源:https://stackoverflow.com/questions/15857203/sequence-contains-no-elements-self-referencing-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!