Entity framework 实体框架嵌套表关系SelectMany
我的问题是以下查询返回零记录。但数据库中有记录 我的目标主题问题通过主题选择表格获得相等的问题模型 我该怎么办。帮你,谢谢 [我的模型] 主题问题Entity framework 实体框架嵌套表关系SelectMany,entity-framework,Entity Framework,我的问题是以下查询返回零记录。但数据库中有记录 我的目标主题问题通过主题选择表格获得相等的问题模型 我该怎么办。帮你,谢谢 [我的模型] 主题问题 public class Question { public int Id { get; set; } public int QuestionNo { get; set; } public string Title { get; set; } public string Description { 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();
List 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()
此时,您正在对SubjectQuestions执行查询,因此EF只显示该表,而不是问题列表。如果你对问题使用Include语句,那应该可以解决它
_db.SubjectQuestions.Include(x => x.Questions).Where(x =>
x.SubjectId == subjectId).ToList()
另外,如果是我,我会在Questions类中明确与SubjectQuestions的关系(包括SubjectQuestion属性和可能的Id)。那么查询就简单了
_db.Questions.Where(x =>
x.SubjectQuestion.SubjectId == subjectId).ToList().Select(y=> y.ToModel())
解决
主题问题
结果还返回零个记录:(您可以连接到我的计算机?如果您将查询分隔开,如var result=\u db.SubjectQuestions.Where(x=>x.SubjectId==SubjectId).ToList()中所示);调试器告诉您关于结果的什么?子问题是否附加了任何问题?可能是因为尽管数据库中有数据,但模型没有正确地提取关系var result=_db.SubjectQuestions.Where(x=>x.SubjectId==SubjectId.ToList();result=22 Count
_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();