1

I have this query below but I'm not sure how to write the query so that I don't have to loop through each yogaSpace and run an individual query.

I'd like to run it all at once in one query. FYI - yogaprofile has a one to many with yogaspaces. yogaspaces has a one to many with yogaspaceevents. And I want all the yogaspaceevents from all the yogaspaces from a single yogaprofile.

using (var dbContext = new YogabandyContext())
        {
            var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserGuid == userId).First();
            var yogaSpaces = yogaProfile.YogaSpaces;
            var today = DateTime.Now.Date;
            foreach (var yogaSpace in yogaSpaces)
            {
                var yogaEvents = yogaSpace.YogaSpaceEvents.Where(k => k.EventDateTime.Date > today.AddDays(-30) && k.EventDateTime < today.AddDays(30));
                // do something with the yogaEvents here
            }
        }
1

2 Answers 2

2

Start your query from YogaSpaces DbSet. This way you can get the result you are expecting from one query executed in the server side:

//Do this outside of your query, a method call can't be translated to sql
var up= DateTime.Now.Date.AddDays(30);
var down= DateTime.Now.Date.AddDays(-30);

var query= dbContext.YogaSpaces
                    .Where(i => i.YogaProfile.ApplicationUserGuid == userId)
                    .SelectMany(i=>i.YogaSpaceEvents.Where(k => k.EventDateTime.Date > down && k.EventDateTime < up));
Sign up to request clarification or add additional context in comments.

Comments

1

Is this what you are looking for?

yogaspaceevents = yogaSpaces.SelectMany(s=>s.YogaSpaceEvents.Where(k
=> k.EventDateTime.Date > today.AddDays(-30) && k.EventDateTime < today.AddDays(30)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.