问题
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