Reputation: 2604
I have two entities in a one-to-many relation: Meter (1) -> (n) Reading
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. Another option could be to read at most X Readings per Meter.
How can I do that in EF.Core?
Upvotes: 0
Views: 233
Reputation: 13773
What I think the other answer missed is that you are asking for a subset of the related entities, i.e. 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.
There is no selective Include
. But you can make an inclusive 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. You can use whatever filter criteria you want here.Include
statement for this. 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.meter.Readings
nav prop. 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()
. Nav props should not be used as storage space for collection with the same type but a different functional meaning.Upvotes: 3
Reputation: 132
If your tables are designed correctly i.e. key in Meter is mapped with Reading (see foreign key constraints), then EF automatically gives related records when you access its POCO class. Make sure Reading has foreign key for Meter table in database.
Upvotes: -1