Should all linq queries which return an entity be surrounded with a try catch?
For example:
phase.Container = containers.Where(cont => cont.ContainerId == phase.ContainerId).SingleOrDefault();
This will not cause the application to crash, but will cause an exception if the Container object is not present.
EDIT
Even doing this will still cause the view to have an exception:
bool schedValid = false;
foreach (var s in schedules)
{
if (s.ScheduleId == phase.ScheduleId) schedValid = true;
}
if (schedValid)
{
phase.Schedule = schedules.SingleOrDefault(sc => sc.ScheduleId == phase.ScheduleId);
}
else
{
phase.Schedule = null;
}
Edit 2
The reason for all this effort is that if a parent object is deleted then the children objects which contain data should still be allowed to be viewed even though their parent is gone. An argument can be made that the parent object should not be allowed to be deleted. Fair enough, but there is no point of keeping it around when the children have become more relevant than the parent and for whatever reason the parent no longer is required to be kept. At a later time, the children may be re-assigned to a different parent object.
This is a response to the question in the title, not the specific example given in the body of the question.
“It depends”
What are you going to do when the exception happens? Can you reasonably respond a database error? If not, don’t catch the exception. If you can reasonable respond in such a way that allows the rest of the application to continue execution, then catch the exception.
See this great post from Eric Lippert for more details about exception handling.
http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx