我正在构建一个用于生成调查和处理响应的系统,我有一个视图模型 SurveyTakeViewModel
namespace Survey.ViewModel
{
public class SurveyTakeViewModel
{
public Models.Survey Survey { get; set; }
public bool TakenBefore { get; set; }
}
}
namespace Survey.Models
{
public class Survey
{
[Key]
public int SurveyId { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public string MessageStart { get; set; }
public string MessageEnd { get; set; }
public virtual ICollection<Question> Question { get; set; }
}
}
namespace Survey.Models
{
public class Question
{
public virtual int SurveyId { get; set; }
[Key]
public int QuestionId { get; set; }
public int DisplayOrder { get; set; }
public string QuestionText { get; set; }
public string QuestionNote { get; set; }
public int QuestionTypeId { get; set; }
public virtual QuestionType QuestionType { get; set; }
public virtual ICollection<QuestionAnswerOption> QuestionAnswerOption{ get; set; }
public virtual ICollection<QuestionAnswer> QuestionAnswer { get; set; }
}
}
namespace Survey.Models
{
public class QuestionAnswer
{
public virtual int QuestionId { get; set; }
[Key]
public int QuestionAnswerId { get; set; }
public int SurveyId { get; set; }
public string UserId { get; set; }
public string QuestionActualResponse { get; set; }
}
}
这一切都适用于问卷调查,但是当用户重新访问他们之前回答过的问卷调查时,我想用特定用户 ID 的答案填充视图模型的 QuestionAnswer 部分,此时我得到每个答案。我尝试了很多不同的 Linq 查询,最初我的 ICollections<> 是 List<>,我被告知这可能会导致所有记录都被返回。
目前我正在使用
Survey = db.Survey.FirstOrDefault(s => s.SurveyId == 1)
返回所有 QuestionAnswer
我尝试过类似的事情
Survey = db.Survey.FirstOrDefault(a => a.Question
.Any(b => b.QuestionAnswer
.Any(c => c.UserId == userId)));
但它仍然为每个 userId 返回所有 QuestionAnswer