Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use a specific record's value that's the many in a 1:many in a query of the parent?

Here’s the classes:

public class Event 
{
    public int Id { get; private set; }

    public List<Occurrence>? Occurrences { get; set; }
}

public class Occurrence
{
    public int Id { get; private set; }

    public Event Parent { get; set; }
    public int ParentId { get; private set; }

    public int RecurrenceIndex { get; set; }
}

What I want to have in my Where() clause is something like:

dbContext.Events
    .Where(e => e.Occurrences[o => o.RecurrenceIndex == index])
    .FirstOrDefaultAsync();

where I pass in index to this query. Obviously [o => o.RecurrenceIndex == index] isn’t valid. But is there a way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can get the Occurrence by doing (writing now so syntax may be wrong):

dbContext.Occurrences
    .Where(o => o.RecurrenceIndex == index)
    .Where(o => o.ParentId == parentId)
    .FirstOrDefaultAsync();

But I’m curious if I can get the parent Event object in a single query.

>Solution :

var event = dbContext.Events
    .Where(e => e.Occurrences.Any(o => o.RecurrenceIndex == index))
    .FirstOrDefaultAsync();

… sounds like it is what you are looking for to get any event that contains a reference to a matching occurrence.
If you want the Occurrences then eager load those to ensure they are available:

var event = dbContext.Events
    .Include(e => e.Occurrences)
    .Where(e => e.Occurrences.Any(o => o.RecurrenceIndex == index))
    .FirstOrDefaultAsync();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading