urlreader
urlreader

Reputation: 6615

Convert this LINQ to Lambda Expression?

I have a LINQ, it works fine. My question is: how to convert it to Lambda Expression?

var searchResults = from study in dataContext.Studies
    join location in dataContext.Locations
        on study.LocationID equals location.LocationID
    join doctorLocation in dataContext.DoctorLocations
        on location.LocationID equals doctorLocation.LocationID
    join doctor in dataContext.Doctors
        on doctorLocation.DoctorID equals doctor.DoctorID
    where doctor.DoctorID == doctorId
    select study;

I think LINQ is more natural to me (similar to SQL script). However, in this case, I just want to convert it to Lambda Expression, but I could not make it work.

I got stuck at:

var searchResults = dataContext.Studies.Where(x => 
  x.Location.DoctorLocations.FirstOrDefault() != null &&
  x.Location.DoctorLocations.FirstOrDefault().DoctorID == doctorId);

This only works for FirstOrDefault. Since there are multiple DoctorLocations, I do not how to write this one.

Upvotes: 0

Views: 788

Answers (2)

ekad
ekad

Reputation: 14624

Try this:

var searchResults = dataContext.Studies.Where(x => 
  x.Location != null 
  && x.Location.DoctorLocations.Any(dl => dl.DoctorID == doctorId));

you will get all Studies related to at least one DoctorLocation with DoctorID equals doctorId

Upvotes: 2

Heberda
Heberda

Reputation: 820

var searchResults = dataContext.Studies
                               .Include(x => x.Locations)
                               .Include(x => x.DoctorLocations)
                               .Include(x => x.Doctors)
                               .Where(x => x.[InheritedPathToDoctor].DoctorId == id)
                               .Select(x => x.[InheritedPathToStudy].Study)
                               .FirstOrDefault() OR .ToList()

I have made a lot of assumptions here as to how you have set up your context. I've assumed it's a relational database and therefore the includes simply means it returns all data. I haven't tested it though so there are probably a few errors.

You require an include for every class and the where is pretty self explanatory.

Upvotes: 0

Related Questions