我的问题是以下查询返回零记录。但是数据库中有记录。
我的目标SubjectQuestion选择Subjectid的表格获得相同的问题模型。
我该怎么办?帮助你谢谢你。
[我的模特]
SubjectQuestion
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);
}
}
QuestionModel
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();
答案 0 :(得分:0)
主要问题在这里
_db.SubjectQuestions.Where(x =>
x.SubjectId == subjectId).ToList()
此时您正在针对SubjectQuestions执行查询,因此EF只会带来该表而不是问题列表。如果您对问题使用Include语句,则应该修复它。
_db.SubjectQuestions.Include(x => x.Questions).Where(x =>
x.SubjectId == subjectId).ToList()
另外,如果是我,我会在你的问题课上明确表达与SubjectQuestions的关系(通过包含一个SubjectQuestion属性,可能还有一个Id)。那么查询就是
_db.Questions.Where(x =>
x.SubjectQuestion.SubjectId == subjectId).ToList().Select(y=> y.ToModel())
答案 1 :(得分:0)
解决
SubjectQuestion
char