实体框架 - 在多个DbSet中导航

时间:2013-02-14 15:18:38

标签: c# entity-framework

假设我有这些模型:

public class TextDocument
{
   public int Id { get; set; }
   public string Name { get; set; }
   public virtual List<Paragraph> Paragraphs { get; set; }
}

public class Paragraph
{
   public virtual TextDocument Document { get; set; } 
   public int Order { get; set; }
   public string Text { get; set; }
}

public class Image
{
    public virtual Paragraph Paragraph {get; set; }
    public virtual TextDocument Document { get; set; } 
    public string Url { get; set }
}

现在,我需要导航TextDocuments中的ParagraphsImagesParagraphsTextDocumentsImages Paragraphs } {},ImagesTextDocuments等等。

如何“连接”模型? 我问的是:

  1. 如何制作DataContext?仅适用于TextDocument?
  2. 有了这个,我如何在不知道Id等的情况下获得所有图像?

2 个答案:

答案 0 :(得分:0)

您的方向正确,看起来您已连接模型。我假设您可以在没有任何问题的情况下浏览属性。

缺少的一件事是Paragraph和Image类的主键定义(Id)。

编辑1:

您只能添加

public DbSet<TextDocument> {get;set;}
在您的DbContext中

,因此您将能够向下导航到图像。同样,您只能在DbContext中放置DbSet for Image,并且您应该能够导航到TextDocument。 你想要达到的目标尚不清楚。 编辑2:

public class Paragraph
{
   public int Id {get; set;} // add this
   public virtual List<Images> Images {get; set;} // and add this
   public virtual TextDocument Document { get; set; } 
   public int Order { get; set; }
   public string Text { get; set; }

}

答案 1 :(得分:0)

问题不明确。 你的模型也有点奇怪。 TextDocument未包含Image列表。但Image包括向ParagraphTextDocument的后退导航。我认为您需要将Image列表添加到Paragraph并从TextDocument中删除Image。这样,您就可以DocumentPharagraphPharagraph拥有Image s;

public class TextDocument
{
   public int Id { get; set; }
   public string Name { get; set; }
   public virtual List<Paragraph> Paragraphs { get; set; }
}
public class Paragraph
{
   public virtual TextDocument Document { get; set; } 
   public int Order { get; set; }
   public string Text { get; set; }
   public virtual List<Image> Images { get; set; }
}
public class Image
{
    public virtual Paragraph Paragraph {get; set; }
    public string Url { get; set }
}

要创建上下文,请创建一个派生自DbContext的类,并添加您的实体集;

public class MyContext : DbContext
{
    public DbSet<Image> Images { get; set; }
    public DbSet<TextDocument> TextDocuments { get; set; }
    public DbSet<Paragraph> Paragraphs { get; set; }
}

获取id等于3的特定文本文档的图像;

using(MyContext context = new MyContext())
{
    var temp = context.TextDocuments.Include("Paragraph.Image").Where(q => q.Id == 3);
    var imageList = temp.Paragraphs.Select(q => q.Images).ToList();
}

选择所有图像;

using(MyContext context = new MyContext())
{
    var allImages = context.Images.ToList();
}

请参阅this blog帖子,其中包含有关EF Code First的良好教程。

相关问题