我有以下实体。
public class Paper
{
public int Id { get; set; }
public string PaperCode { get; set; }
...
}
public class MCQPaper : Paper
{
public ICollection<MCQQuestion> Questions { get; set; }
}
public class MCQQuestion : Question
{
public int MCQPaperId { get; set; }
public MCQPaper MCQPaper { get; set; }
public int? MCQOptionId { get; set; }
[ForeignKey("MCQOptionId")]
public MCQOption TrueAnswer { get; set; }
public ICollection<MCQOption> MCQOptions { get; set; }
}
public class MCQOption
{
public int Id { get; set; }
public string OptionText { get; set; }
}
我正在尝试基于唯一的papercode获取MCQPaper,但它总是给我空集的问题
这是我在存储库中的查询。
public MCQPaper GetByPaperCode(string paperCode)
{
var ans = AppDbContext.MCQPapers
.Where(paper => paper.PaperCode.Equals(paperCode))
//.Include(paper => paper.Questions)
// .ThenInclude(que => que.MCQOptions)
.Include(paper => paper.Questions)
.ThenInclude(que => que.MCQPaper)
//.Include(paper => paper.Questions)
// .ThenInclude(que => que.TrueAnswer)
.FirstOrDefault();
return ans;
}
在这里,我尝试了include()和theninclude()的各种组合,但是它们都不适合我
最后忽略语法错误(如果有的话)
先谢谢
答案 0 :(得分:0)
发表评论并在Google上搜索后,我找到了解决方法
使用两个查询可以解决此问题,因为这里我在MCQQuestion
和MCQOption
之间具有循环依赖关系
所以解决方案是....
public MCQPaper GetByPaperCode(string paperCode)
{
using var transaction = AppDbContext.Database.BeginTransaction();
MCQPaper ans = new MCQPaper();
try
{
ans = AppDbContext.MCQPapers
.FirstOrDefault(paper => paper.PaperCode.Equals(paperCode));
var questions = AppDbContext.MCQQuestions
.Include(que => que.MCQOptions)
.Where(que => que.MCQPaperId == ans.Id);
ans.Questions = questions.ToList();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
return ans;
}