我的问题是以下查询返回零条记录。但是数据库中有记录。
我的目标 主题问题 通过主题 id 选择表得到相等的问题模型。
我该怎么做。帮你谢谢。
[我的模特]
主题问题
public class SubjectQuestion
{
public int Id { get; set; }
public int SubjectId { get; set; }
public int QuestionId { get; set; }
public virtual List<Question.Question> Question { get; set; }
}
问题
public class Question
{
public int Id { get; set; }
public int QuestionNo { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsDeleted { get; set; }
public QuestionModel ToModel()
{
return new QuestionModel(Id,QuestionNo,Title,Description,ChoiceId);
}
}
问题模型
public class QuestionModel
{
public QuestionModel(int id, int questionNo, string title, string description,int choiceid)
{
Id = id;
QuestionNo = questionNo;
Title = title;
Description = description;
ChoiceId = choiceid;
}
public int Id { get; set; }
public int QuestionNo { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsDeleted { get; set; }
}
实体框架查询
List<QuestionModel> lst = _db.SubjectQuestions.Where(x => x.SubjectId == subjectId).ToList().SelectMany(r=> r.Question.Select(y=> y.ToModel()).ToList()).ToList();
主要问题就在这里
_db.SubjectQuestions.Where(x =>
x.SubjectId == subjectId).ToList()
此时,您仅针对主题问题执行查询,因此 EF 仅显示该表,而不是问题列表。如果您为问题使用 Include 语句,那应该可以解决它。
_db.SubjectQuestions.Include(x => x.Questions).Where(x =>
x.SubjectId == subjectId).ToList()
此外,如果是我,我会在您的 Question 类中明确说明与 SubjectQuestions 的关系(通过包含 SubjectQuestion 属性和可能的 Id)。那么查询将只是
_db.Questions.Where(x =>
x.SubjectQuestion.SubjectId == subjectId).ToList().Select(y=> y.ToModel())
已解决
主题问题
public class SubjectQuestion
{
public int Id { get; set; }
public int SubjectId { get; set; }
public int QuestionId { get; set; }
public virtual Question.Question Question { get; set; } //Change one to one
}
list = _db.QuestionSubjects.Where(i => i.SubjectId == subjectId).ToList().Select(x => x.Questions.ToModel()).ToList();