我有一个LINQ,它工作正常。我的问题是:如何将其转换为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;
我认为LINQ对我来说更自然(类似于SQL脚本)。但是,在这种情况下,我只想将其转换为Lambda Expression,但我无法使其正常工作。
我被卡住了:
var searchResults = dataContext.Studies.Where(x =>
x.Location.DoctorLocations.FirstOrDefault() != null &&
x.Location.DoctorLocations.FirstOrDefault().DoctorID == doctorId);
这仅适用于FirstOrDefault。由于有多个DoctorLocations,我不知道如何写这个。
答案 0 :(得分:2)
试试这个:
var searchResults = dataContext.Studies.Where(x =>
x.Location != null
&& x.Location.DoctorLocations.Any(dl => dl.DoctorID == doctorId));
您将获得与Studies
等于DoctorLocation
的至少一个DoctorID
相关的所有doctorId
答案 1 :(得分:0)
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()
我在这里已经做了很多关于如何设置上下文的假设。我假设它是一个关系数据库,因此包含只是意味着它返回所有数据。我没有测试它,所以可能有一些错误。
你需要为每个班级提供一个包含,并且其中的地方非常自我解释。