为什么实体不会自动完成关系?

时间:2012-05-05 00:57:10

标签: c# entity-framework

我有三个模型:DocumentSectionParagraph。每个人都是这样的。

// 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 == IdDocument.Sections虽然没有发生这种情况。 Document.Sections的所有部分都填充DocumentId == id,而Document.Sections为空,而不是{{1}}。哎呀!

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)吗?