0

I have two and more related tables in my project. And need to get related objects.

Here is what I did: http://pastebin.com/BbkT8zvd

And trying to get like this:

using (LocalContext _db = new LocalContext())
{
    var list = _db.Document.ToList();
    foreach (var item in list)
    {
        Console.WriteLine(item.Name+ ": ");
        foreach (var item2 in item.Comment)
        {
            Console.WriteLine(item2.CommentText);
        }
    }       
}

It returns no comments related with documents.

Tried Lazy, Eager and Explicit loading methods.

What should I correct in my code?

tereško
  • 58,060
  • 25
  • 98
  • 150
John
  • 49
  • 2
  • 7

3 Answers3

3

You can use eager loading for getting related entities, Eager loading is achieved by use of the Include method:

_db.Document.Include("Comment").ToList();

More info

Update: You don't need to initialize Document in the Comment class, Your Comment class should be like this:

public class Comment
{
    public int Id { get; set; }
    public int DocId { get; set; }
    public string CommentText { get; set; }
    public virtual Document Document { get; set; } 
}

Document class:

public class Document
{
    public Document()
    {
        this.Comment = new HashSet<Comment>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Comment> Comment { get; set; } 
}

And the query:

var list = _db.Document.Include("Comment").ToList();

In this case all related comments will be loaded.

Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
  • Initializing `Document` in `Comment`'s constructor is the key to this problem. It blocks relationship fixup. See also [this Q&A](http://stackoverflow.com/q/20757594/861716) that I updated to cover this case here. – Gert Arnold Sep 09 '15 at 20:46
2

As I see in your codes, you have disabled lazy loading Configuration.LazyLoadingEnabled = false;. So you need include child items this way:

_db.Document.Include("Comment").ToList()

You can consider reading:

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0

Rename the DocId property in your Comment class to DocumentId - when using CodeFirst approach you have to be careful about these namings.

LazyLoading set to true should normally do the trick. Try setting it and also include the navigation property in your call:

_db.Document.Include("Comment").ToList

PS: It is a good convention to use plural names for your tables and dbsets

stann1
  • 576
  • 3
  • 11