6

It is clear how to query an entity and include all the related data; e.g.:

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .Include(blog => blog.Owner)
        .ToList();
}

REF

My question is, given an entity that is missing some related data, how I can ask EF to fetch its related data from DB?

For instance:

var blog = context.Blogs.Find(1); // get the blog with ID=1

// how can I do something like:
blog.Include(x => x.Posts);
2
  • 1
    learn.microsoft.com/en-us/ef/core/querying/… Commented Jan 25, 2020 at 11:28
  • @GertArnold Your link to the documentation for explicit loading is the correct answer to this question. You should re-submit it as an Answer rather than as a Comment. Commented Jan 25, 2020 at 17:55

3 Answers 3

7
context.Entry(blog).Collection(x => x.Posts).Load();
context.Entry(blog).Reference(x => x.Owner).Load();

According to this reference, as suggested by @GertArnold

Sign up to request clarification or add additional context in comments.

Comments

3

As microsoft said, the retun dataType of Find() method is TEntity.

public virtual TEntity Find (params object[] keyValues);

and It means that Find() method hit the database and will fetch a TEntity. So you can't extend your query after Find() method. hence, If you wanna get related data in this query you must call Include() before any method which hit the database. as like as below query:

var blog = context.Blogs.Include(x => x.Posts).SingleOrDefault(x => x.Id == 1);

As a conclusion, The way that you expected to do with Includ() is not possible, but if you have to do this as @GertArnold said in comment, you can follow this way.

good luck.

Comments

-2

try to use this

var blog = context.Blogs.Include(x => x.Posts).FirstOrDefault(x => x.Id == 1);

3 Comments

Maybe the question was not clear, I mean, I don't want to use Blogs anymore, for application reasons.
it was I suppose. why don't you query from "Posts" DbSet directly? something like this context.Posts.FirstOrDefault(x => x.BlogId== 1);
It is eager loading. To solve this problem need explicit loading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.