IQueryable Linq To SQL with multiple operators
I'm creating a repository and service layer in my app, and my repo has a very simple function
Public Function GetRegions() As IQueryable(Of Region) Implements IRegionRepository.GetRegions
Dim region = (From r In dc.Regions
Select r)
Return region.AsQueryable
End Function
Now in my Service layer I've 开发者_开发技巧got a function like this
Public Function GetRegionById(ByVal id As Integer) As Region Implements IRegionService.GetRegionById
Return _RegionRepository.GetRegions().Where(Function(r) r.ID = id).FirstOrDefault
End Function
But i can't figure out how to add And r.isActive = True
Can anyone point me in the right direction on how to have multiple operators in this query?
You need to put your predicate inside of ()
Like so
Public Function GetRegionById(ByVal id As Integer) As Region Implements IRegionService.GetRegionById
Return _RegionRepository.GetRegions() _
.Where(Function(r) (r.ID = id And r.isActive = True)).FirstOrDefault
End Function
The reason for this is it has to return as a boolean. Edit in response to the comments I'm not 100% on this but I think your way performs a where twice for each object, basically it'sgoing to always do an and and compare both values against the queried object, where mine will only compare until a condition is false. Also I'm not sure if you can perform Or operations using your method.
Not a vb guy as much as c# but the expression used in the where statement should be where it is appended. So you currently have r.ID = id. I would just add it there. So it would be: (pseudo code) r.Id = id AND r.IsActive = True
This seems to be working the way I want it to.
Public Function GetRegionById(ByVal id As Integer) As Region Implements IRegionService.GetRegionById
Return _RegionRepository.GetRegions() _
.Where(Function(r) r.ID = id) _
.Where(Function(r) r.isActive = True) _
.FirstOrDefault()
End Function
精彩评论