I have been using linq in combination with entity framework for a few months now and am wondering about subqueries vs joins.
I am using subqueries a lot like this:
(from department in
(from hospital in hospitalRepository.Hospitals
where hospital.Id == viewModel.DestinationHospitalId
select hospital.Departments).Single()
select new { Value = department.Id, Text = department.Name }).ToList();
I never really use the join keyword because to me it feel a bit too databasey. I think to do the join I need foreign keys in my domain objects which I don't really like and I feel subqueries are more intuitive. However, I almost always see people use joins in linq, which makes me wonder whether joins are much better or that people are just used to using joins from SQL.
Furthermore, I ran into a problem with my subqueries that when the Hospitals
ObjectSet doesn't contain a hospital with the id I want. I don't know how to make the subquery return an empty collection. Apparently the default for a list is null
. Now I use Single and catch the exception, however I would prefer that my query would just开发者_如何学编程 return an empty list.
Should I just start using joins? Shouldn't I want my query to return an empty list and handle that case as an exception? Would it have been better if the default for a list would have been an empty one?
Some background: The purpose of this query is to populate a dropdownbox in my view based on a selected value of another dropdownlist. The other dropdownlist could have no selection which would require the first dropdownlist to be empty. So it's not really an exception.
Thanks in advance.
I would definitely start embracing joins if I were you. Fundamentally if you've got two collections, and want to find corresponding rows based on some ID, then that's exactly what a join is for. Don't think about it in terms of databases - think of it in terms of matching.
I'm not entirely sure you need it in this case, mind you... I suspect you'd be fine with:
from hospital in hospitalRepository.Hospitals
where hospital.Id == viewModel.DestinationHospitalId
from department in hospital.Departments
select new { Value = department.Id, Text = department.Name }
Here, if there are no matching results you will end up with an empty list, so that deals with the problem for you. However, you should also be aware of some alternatives to Single
for other situations:
First
FirstOrDefault
SingleOrDefault
精彩评论