如何从C#查询中的嵌套关​​系表链接数据

问题描述

我有一个模拟设计时IList静态数据结构,该结构镜像将存储在生产数据库中的内容。该模型具有一对多关系(一个读数包含许多度量值),但也具有链接的多对一关系(度量值属于MeasurementType)。我需要返回一个IEnumerable of Reading,每个条目都包含其Measurements列表,而且每个Measurement需要MeasurementType对象包含MeasurementTypes列表中的相关对象。

模型类中的Measurements和Type属性不会保留在数据库中。

我可以看到如何使用“测量值”列表属性将“测量值”列表返回到我的应用程序,该属性由“测量值”列表中的匹配对象填充,但是正在努力为每种测量值的“类型”属性填充相关的读数的最佳方法基于id属性从MeasurementTypes列表中选择对象,因此我还可以过滤出measementType未设置为visible的Measurement对象。

以下查询失败,因为Type属性为null,我如何通过Id从MeasurementTypes列表中加入Type对象,以便可以在查询中使用它?还是有比在foreach循环中查询更好的方法呢?

foreach (var reading in readings)
{
    reading.Measurements = measurements.Where(m => (m.ReadingId == reading.Id) && (m.Type.Visible)).ToList();
}

return readings;

(为清楚起见,简化了类)

public class Reading
{
    public DateTime DateTime { get; set; }
    public int Id { get; set; }
    public IList<Measurement>? Measurements { get; set; }
}

public class Measurement
{
    public int MeasurementTypeId { get; set; }
    public int ReadingId { get; set; }
    public MeasurementType? Type { get; set; }
    public int Value { get; set; }
}  

public class MeasurementType
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public bool Visible { get; set; }
}

measurementTypes = new List<MeasurementType>()
{
    new MeasurementType { Id = 1,Name = "A name",Visible = true }
    ...
};

measurements = new List<Measurement>()
{
    new Measurement { ReadingId = 1,MeasurementTypeId = 1,Value = 100 }
    ...
};

readings = new List<Reading>()
{
    new Reading { Id = 1,DateTime = DateTime.Today.AddDays(-366) }
...
};

解决方法

Measurement和MeasurementType之间的关系必须手动建立。 您需要从MeasurementType列表中的相关值之一分配 Type 字段。 您可以尝试的一种方法如下:

在Measurement中引入一个构造函数

    public class Measurement
    {
        // for mock tests
        public Measurement(int measurementTypeId,int readingId,int value,IEnumerable<MeasurementType> measurementTypes)
        {
            MeasurementTypeId = measurementTypeId;
            ReadingId = readingId;
            Type = measurementTypes.Single(mt=>mt.Id==measurementTypeId),Value = value;
        }

        public int MeasurementTypeId { get; set; }
        public int ReadingId { get; set; }
        public MeasurementType Type { get; set; }
        public int Value { get; set; }
    }

然后在建立测量列表时:

measurementTypes = new List<MeasurementType>()
{
    new MeasurementType { Id = 1,Name = "A name",Visible = true }
...
};

measurements = new List<Measurement>()
{
    new Measurement (1,1,100,measurementTypes) 
 ....
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...