【问题标题】:How do I add/update the child of a child in C# using Entity Framework Core?如何使用 Entity Framework Core 在 C# 中添加/更新孩子的孩子?
【发布时间】:2021-08-10 17:53:19
【问题描述】:

This 答案对于在更新父实体时更新子实体很有用。我现在正在尝试更新一个孩子的孩子。下面用于查找哪些子记录(如果有)属于父记录,以便可以添加/更新记录。

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 个问题。

如何做到这一点?

【问题讨论】:

  • 您只是在查询数据,而不是在更新。显示不符合您要求的代码。
  • 为了获得更多信息,您需要提供数据表图。
  • 请编辑您的问题并将您的表格的相关部分提供给我们。还给我们关系:校准是否有零个或多个症状?还是一个症状有几个 Clibrate?
  • 对不起,伙计们。我将我的实体添加到问题中。

标签: c# .net linq entity-framework-core


【解决方案1】:

也许就像使用.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 (Non-null reference navigations are not overwritten by queries) 最近的重大更改有关: .Include(...) 只会设置数据库中的相关项目,如果您的导航属性仍然​​为空。由于您在这里初始化了SymptomsSymptomsQuestions.Include() 可能什么都不做。

旁注: 为什么称一个实体为“Symptom”(单数)而另一个为“SymptomQuestions”(= 复数)?两者似乎只代表一个实例。

【讨论】:

    猜你喜欢
    • 2010-11-25
    • 2021-07-21
    • 2022-11-13
    • 2022-08-17
    • 2015-01-07
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多