2013-02-14 78 views
1

比方說,我有這些模型:實體框架 - 瀏覽多個DbSets

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瀏覽,ParagraphsImagesParagraphsTextDocumentsImagesParagraphsImagesTextDocuments等。

如何「連接」模型? 我在問什麼是:

  1. 如何使DataContext?僅用於TextDocument?
  2. 有了這個,我如何得到,例如,所有的圖像不知道Id的等?

回答

0

問題不明確。 另外你的模型有點奇怪。 TextDocument不包括Image的列表。但Image都包括後面導航到ParagraphTextDocument。我認爲您需要將Image列表添加到Paragraph並從Image刪除TextDocument。通過這種方式,您將使Document s具有Pharagraph s和Pharagraph s具有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代碼首先一個很好的教程。

+0

謝謝,它解決了我的問題!我不知道LINQ包含命令,但現在它是有道理的! – josefpospisil0 2013-02-14 15:41:46

+0

@ josefpospisil0我已經更新了這個問題。 – daryal 2013-02-14 15:56:13

+0

謝謝,這就是我想要得到的。 – josefpospisil0 2013-02-14 16:05:36

0

您處於正確的方向,看起來像您已連接模型。我假設你可以通過這些屬性進行導航,而不會對這個類定義產生任何問題。

缺少的一件事是Paragraph和Image類的主鍵定義(Id)。

編輯1:

你只能在你的DbContext添加

public DbSet<TextDocument> {get;set;} 

,這樣的話你就可以向下導航到圖片。同樣,您只能將DbSet for Image放置在DbContext中,並且應該能夠導航到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; } 

} 
+0

謝謝您的回覆,我編輯了這個問題。 – josefpospisil0 2013-02-14 15:36:33