In the course of adding exception handling for occasional SQL problems (random timeouts, etc.) to my various queries in my EF4 web app, I’ve really got to refactor the common exception handling code into one function to maintain. But I do lots of different kinds of LINQ queries on different entities.
My first pass at this is close, I think. In this example, I have two overloaded functions that take different kinds of parameters that do a very similar database query:
public bool check_person(string name)
{
return CheckInternal(people.Where(x => x.user_name == name));
}
public bool check_person(Guid ID)
{
return CheckInternal(people.Where(x => x.user_ID == ID));
}
protected bool CheckInternal(IQueryable<people> peepQuery)
{
try
{
return(peepQuery).Any(); //causes actual db query
}
catch (Exception ue)
{ blah blah retry blah blah }
}
So I’m just pushing the actual enumeration to the CheckInternal function that has all kinds of fancy exception handling and retry logic in it which is totally independent of the query or even the table being queried.
Now the drawback here is that I can only pass in an IQueryable<people> but I want to be able to pass in an IQueryable on lots of different entity types other than the people type.
I tried wrapping my head around lambdas to allow me to pass in any kind of query on any entity type and have just one wiz-bang exception handler to maintain, but I’m just not there yet with my lambda and delegate knowledge. I can’t figure it out.
Can someone give me a hint? What if I had another function that wanted to do a query on the widgets table and pass it to CheckInternal? It’s critical that the actual enumeration only happen in the CheckInternal function since that’s where the exception will be thrown.
If the return type stays a boolean and you just want to query different entities in your example you could make
CheckInternalgeneric and change the signature as follows:Then you could call it like this