简体   繁体   中英

How to retrieve entities with a subset of related entities?

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?

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.

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

  • I used an anonymous type, but you can of course also use a concrete DTO class.
  • 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.
  • Notice that you do not need an 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.
  • I suggest not putting the subset of related entities in the 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.

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. Make sure Reading has foreign key for Meter table in database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM