[英]How to retrieve entities with a subset of related entities?
I have two entities in a one-to-many relation: Meter (1) -> (n) Reading 我有一对多关系中的两个实体:仪表(1)->(n)阅读
I believe my two entities are set up correctly to provide the relation, so assume that. 我相信我的两个实体已正确设置以提供该关系,因此假设这一点。
I wish to retrieve Meters with related Readings but because there may be many Readings per Meter, I wish to limit it by eg Reading.Date. 我希望检索具有相关读数的仪表,但是由于每个仪表可能有很多读数,因此我希望通过例如Reading.Date来限制它。 Another option could be to read at most X Readings per Meter.
另一个选择是每米最多读取X个读数。
How can I do that in EF.Core? 如何在EF.Core中做到这一点?
What I think the other answer missed is that you are asking for a subset of the related entities, ie not the entire collection of related entities. 我认为错过的另一个答案是,您要的是相关实体的子集 ,而不是相关实体的整个集合。
If you want to be selective about the related entities that are fetched, you cannot just rely on an Include
statement (or implicit lazy loading), because these are set up to load all related entities. 如果要对提取的相关实体保持选择性,则不能仅依靠
Include
语句(或隐式延迟加载),因为它们被设置为加载所有相关实体。
There is no selective Include
. 没有选择性的
Include
。 But you can make an inclusive Select
: 但是您可以
Select
一个包容性的Select
:
DateTime filterDate = DateTime.Now;
var myData = db.Meters
.Select(m => new
{
Meter = m,
Readings = m.Readings.Where(r => r.Date == filterDate)
})
.ToList();
Remarks 备注
Where(r => r.Date == filterDate)
can be improved (checking for the Date
component, or a range), this is just a simple example. Where(r => r.Date == filterDate)
可以改进(检查Date
组件或范围),这只是一个简单的示例。 You can use whatever filter criteria you want here. Include
statement for this. Include
语句。 A Select
(on a yet unenumerated IQueryable
) does not need an explicit Include
because the Select
itself is already aware of what data you want to fetch. Select
(在尚未枚举的IQueryable
)不需要显式的Include
因为Select
本身已经知道您要获取的数据。 meter.Readings
nav prop. meter.Readings
。 This is going to lead to confusion down the line as to whether this list is a subset or the full set, and EF may actually register this as a change when you call SaceChanges()
. SaceChanges()
时,EF实际上可能会将其注册为更改。 Nav props should not be used as storage space for collection with the same type but a different functional meaning. If your tables are designed correctly ie key in Meter is mapped with Reading (see foreign key constraints), then EF automatically gives related records when you access its POCO class. 如果您的表设计正确,即Meter中的键已与Reading映射(请参阅外键约束),则EF在访问其POCO类时会自动提供相关记录。 Make sure Reading has foreign key for Meter table in database.
确保读数具有数据库中仪表表的外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.