John
John

Reputation: 89

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?

Upvotes: 4

Views: 3087

Answers (3)

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

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.

Upvotes: 6

Reza Aghaei
Reza Aghaei

Reputation: 125197

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:

Upvotes: 2

stann1
stann1

Reputation: 635

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

Upvotes: 0

Related Questions