josefpospisil0 josefpospisil0 - 3 months ago 8
C# Question

Entity Framework - Navigate in multiple DbSets

Let's say that I have these models:

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 }
}


And now, I need to navigate in
TextDocuments
,
Paragraphs
,
Images
,
Paragraphs
in
TextDocuments
,
Images
in
Paragraphs
,
Images
in
TextDocuments
, etc.

How do I "connect" the models?
What I'm asking is:


  1. How to make the DataContext? Only for the TextDocument?

  2. With this, how do I get, for example, all Images without knowing the Id's, etc?


Answer

The question is not clear. Also your model is a bit strange. TextDocument does not include a list of Images. But Image both includes back navigations to Paragraph and TextDocument. I think you need to add Image list to Paragraph and remove TextDocument from Image. This way you will enable Documents to have Pharagraphs and Pharagraphs to have Images;

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 }
}

To create a context create a class deriving from DbContext, and add your entity sets;

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

to fetch the images of a specific text document with id equals to 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();
}

to select all images;

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

Refer to this blog post which has a good tutorial about EF Code First.