簡體   English   中英

實體為什么不自動完成關系?

[英]Why isn't Entity automatically completing the relationship?

我有三種模型: 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 == Id所有段落填充到Section.Paragraphs 但是對於Document.Sections卻沒有發生。 取而代之的Document.Sections被填充的所有部分,其中DocumentId == idDocument.Sections為空。 啊!

添加以下注釋:

// 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)可能存在問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM