我有三个模型:Document
,Section
和Paragraph
。每个人都是这样的。
// Document
public class Document
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Section> Sections { get; set; }
}
// Section
public class Section
{
public int Id { get; set; }
public int DocumentId { get; set; }
public virtual Document Document { get; set; }
public virtual ICollection<Paragraph> Paragraphs { get; set; }
}
// Paragraph
public class Paragraph
{
public int Id { get; set; }
public int SectionId { get; set; }
public virtual Section Section { get; set; }
}
实体会自动填充Section.Paragraphs
所有段落SectionId == Id
。 Document.Sections
虽然没有发生这种情况。 Document.Sections
的所有部分都填充DocumentId == id
,而Document.Sections
为空,而不是{{1}}。哎呀!
答案 0 :(得分:0)
添加以下注释:
// Document
public class Document
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Document")]
public virtual ICollection<Section> Sections { get; set; }
}
// Section
public class Section
{
[Key]
public int Id { get; set; }
[ForeignKey("Document")]
public int DocumentId { get; set; }
public virtual Document Document { get; set; }
[InverseProperty("Section")]
public virtual ICollection<Paragraph> Paragraphs { get; set; }
}
// Paragraph
public class Paragraph
{
[Key]
public int Id { get; set; }
[ForeignKey("Section")]
public int SectionId { get; set; }
public virtual Section Section { get; set; }
}
我也会考虑这个:
public class YourContext : DbContext
{
public DbSet<Document> Documents {get;set;}
public DbSet<Paragraph> Paragraphs {get;set;}
public DbSet<Section> Sections {get;set;}
}
告诉我它是否以任何方式帮助了你。如何加载实体可能存在问题(您使用Include)吗?