Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework 6. How to get related objects?

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?

like image 356
John Avatar asked Oct 22 '25 04:10

John


1 Answers

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.

like image 185
Sirwan Afifi Avatar answered Oct 24 '25 18:10

Sirwan Afifi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!