[英]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.