Asp.Net Core Entity Framework doesn't load relational data
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
{
[Key]
public int QuestionId { get; set; }
public string Content { get; set; }
public IEnumerable<Answer> Answers { get; set; }
}
public class Answer
{
[Key]
public int AnswerId { get; set; }
public string Content { get; set; }
[ForeignKey("Question")]
[JsonIgnore]
public int QuestionId { get; set; }
[JsonIgnore]
public Question Question { get; set; }
}
QuestionsController is the controller that I use to get the data
[HttpGet]
public IActionResult Get()
{
return Ok(_context.Questions.ToList());
}
Please help me resolve this issue.
-
D0
Dung Do Tien Jan 28 2021
Actually, Entity Framework provides us 3 ways to get relational data
- LazyLoading
- EagerLoading
- ExplicitLoading
You can get more information here.
For your question. You can use
EagerLoading
to load all relational dataJust change
_context.Questions
to_context.Questions.Include(t=>t.Answers)
to resolve the question.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.