[英]Child Table Properties are not fetching in ef core inheritance
i have following entities..我有以下实体..
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; }
}
and i am trying to fetch MCQPaper based on unique papercode but it always gives me empty collection of Questions我正在尝试根据唯一的 papercode 获取 MCQPaper,但它总是给我空的问题集合
here is my Query inside Repository..这是我在存储库中的查询..
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;
}
here i have tried various combinations of include() and theninclude() but none of them work for me在这里,我尝试了 include() 和 theninclude() 的各种组合,但没有一个对我有用
and lastly ignore grammer mistakes if any最后忽略语法错误(如果有的话)
thankyou in advance先感谢您
after going threw comments and searching on google i have found solution在发表评论并在谷歌上搜索后,我找到了解决方案
using two queries this problem can be solved because here i have circular dependency between MCQQuestion
and MCQOption
使用两个查询可以解决这个问题,因为这里我在MCQQuestion
和MCQOption
之间有循环依赖
so solution is ....所以解决方案是......
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.