Asp.Net Core Entity Framework doesn't load relational data

Dung Do Tien Jan 28 2021 497

I'm working with EntityFrameworkCore 3.1.

I wanna get some data from the database but. The result doesn't contain relational information

I made 2 simple Entity called: Question and Answer. Each question has some answers.

So what I need to do is when retrieving data from the database, each question includes all information about the answer.

I wanna show my code:

public class Question
    public int QuestionId { get; set; }
    public string Content { get; set; }
    public IEnumerable<Answer> Answers { get; set; }

public class Answer
    public int AnswerId { get; set; }
    public string Content { get; set; }

    public int QuestionId { get; set; }
    public Question Question { get; set; }

QuestionsController is the controller that I use to get the data

public IActionResult Get()
    return Ok(_context.Questions.ToList());

Please help me resolve this issue.

Have 1 answer(s) found.
  • D

    Dung Do Tien Jan 28 2021

    Actually, Entity Framework provides us 3 ways to get relational data

    1. LazyLoading
    2. EagerLoading
    3. ExplicitLoading

    You can get more information here.

    For your question. You can use EagerLoading to load all relational data

    Just change _context.Questions to _context.Questions.Include(t=>t.Answers) to resolve the question.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close