[英]How do I add/update the child of a child in C# using Entity Framework Core?
此答案对于在更新父实体时更新子实体很有用。 我现在正在尝试更新一个孩子的孩子。 以下用于查找哪些子记录(如果有)属于父记录,以便可以添加/更新记录。
var calFile = await innerContext.Calibrate
.Where(x => x.DataId == dataFile.Id)
.Include(x => x.Symptom)
.SingleOrDefaultAsync();
这不适用于添加/更新孩子的孩子:
var calFile = await innerContext.Calibrate
.Where(x => x.DataId == dataFile.Id)
.Include(x => x.Symptom)
.Include(x => x.SymptomQuestions
.SingleOrDefaultAsync();
我的实体如下:
public class Calibrate : IAnalyticsSection
{
public int Id { get; set; }
public Guid DataFileId { get; set; }
public bool TestType { get; set; }
public decimal Height { get; set; }
public decimal CalibratedHeadPosition { get; set; }
public decimal LeftHandPositionTPose { get; set; }
public decimal RightHandPositionTPose { get; set; }
public decimal LeftHandSpherePos { get; set; }
public decimal RightHandSpherePos { get; set; }
public ICollection<Symptom> Symptoms { get; set; } = new List<Symptom>();
public virtual DataFile DataFile { get; set; }
}
public class Symptom
{
public int Id { get; set; }
public int CalibeId { get; set; }
public int SymptomSeverity { get; set; }
public virtual ICollection<SymptomQuestions> SymptomQuestions { get; set; } = new List<SymptomQuestions>();
public virtual Calibrate Calibrate { get; set; }
}
public class SymptomQuestions
{
public int Id { get; set; }
public int SymptomsId { get; set; }
public int Question { get; set; }
public int Answer { get; set; }
public virtual Symptom Symptoms { get; set; }
}
校准可以有几个症状,每个症状都有 5 个问题。
如何才能做到这一点?
也许就像使用.ThenInclude(..)
一样简单:
var calFile = await innerContext.Calibrate
.Where(x => x.DataId == dataFile.Id)
.Include(x => x.Symptom)
.ThenInclude(x => x.SymptomQuestions)
.SingleOrDefaultAsync();
但也许我们也需要查看关系的定义(FluentAPI?)?
或者您的问题与最近对 EF Core 5.0 的重大更改有关( 非空引用导航不会被查询覆盖): .Include(...)
只会设置数据库中的相关项目,如果您的导航属性仍然是 null . 由于您在此处初始化了Symptoms
和SymptomsQuestions
问题, .Include()
可能什么也不做。
旁注:为什么称一个实体为“Symptom”(单数)而另一个为“SymptomQuestion s ”(= 复数)? 两者似乎只代表一个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.