【发布时间】:2020-09-16 11:51:15
【问题描述】:
我有一个模拟设计时 IList 静态数据结构,用于镜像将存储在生产数据库中的内容。该模型具有一对多的关系(读数包含许多测量),但也具有链接的多对一(测量属于 MeasurementType)。我需要返回一个读取的 IEnumerable,其中每个条目都包含其测量值列表,而且每个测量值都需要 MeasurementType 对象以包含 MeasurementTypes 列表中的相关对象。
模型类中的 Measurements 和 Type 属性不会保存在数据库中。
我可以看到如何将读数列表返回到我的应用程序,其中测量列表属性填充了测量列表中的匹配对象,但我正在努力寻找在每个测量中填充 Type 属性以使用相关的读数的最佳方法基于 id 属性的measurementTypes 列表中的对象,因此我还可以过滤掉measementType 未设置为可见的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) }
...
};
【问题讨论】:
-
(m.ReadingId == reading.Id) && (m.Type != null) && (m.Type.Visible)
标签: c# linq non-relational-database