我是Entity Framework Core的新手,在我的代码中,我有许多Questions
类对象,以及这些问题的选择列表。我的查询列表Choices
始终返回Null。
这是我的课程:
public class Questions
{
[Key]
public int QuestionID { get; set; }
public string Question { get; set; }
public ICollection<Choices> choices { get; set; }
}
public class Choices
{
[Key]
public int ChoicesId { get; set; }
public int QuestionId { get; set; }
public Questions questions { get; set; }
public string Choice { get; set; }
}
public class SqlUserRepository : IUserRepository
{
private readonly AppDbContext context;
public SqlUserRepository(AppDbContext context)
{
this.context = context;
}
public List<Questions> getAllQuestions()
{
return context.questions.ToList();
}
}
我正在获取此O / p。选择总是返回null
[
{ "questionID":1, "question":"which is your fav.heroien", "choices":null },
{ "questionID":2, "question":"which is your fav.hero", "choices":null }
]
我希望这个输出
[{"questionID":1,"question":"which is your fav.heroien","choices":[{"choicesId":5,"questionId":1,"questions":null,"choice":"kajol Agarwal"},{"choicesId":6,"questionId":1,"questions":null,"choice":"Thammanna Bhatia"},{"choicesId":7,"questionId":1,"questions":null,"choice":"Anushka Shetty"},{"choicesId":8,"questionId":1,"questions":null,"choice":"Keerthi Suresh"}]},{"questionID":2,"question":"which is your fav.hero","choices":[{"choicesId":1,"questionId":2,"questions":null,"choice":"upendera"},{"choicesId":2,"questionId":2,"questions":null,"choice":"real star"},{"choicesId":3,"questionId":2,"questions":null,"choice":"Super star"},{"choicesId":4,"questionId":2,"questions":null,"choice":"Only star"}]}]
答案 0 :(得分:0)
public List<Questions> getAllQuestions()
{
return context.questions.Include(q => q.choices).ToList();
}
Include()允许您指示应在同一查询中从数据库中读取哪些相关实体。
调用Include(“ Choices”)的最终语句可能如下所示:
SELECT *
FROM questions JOIN Choices ON questions.Id = Choices.questionsId;
答案 1 :(得分:0)
如何使用代码优先方法和关系数据构建应用程序,link将逐步指导应用代码优先方法的事情。
答案 2 :(得分:0)
根据EF Core-Loading Related Data文档,您必须使用.Include
来加载相关数据,如下所示:
public List<Questions> getAllQuestions()
{
return context.questions.Include(q => q.choices).ToList();
}