I have a method in my project that repeats over and over:
public PAC PAC_GetByCodiPac(string codiPac)
{
var sel = _gam.PAC.Where(pac => pac.CODI_PAC == codiPac);
if (sel.Count() > 0)
return sel.First();
return null;
}
The table PAC means (patient), so I have these methods for all the tables I have.
How can I make a generic method for this?
Thanks in advance.
If you want a generic method that lets you specify any table and any predicate for records from that table then you can’t really get any better than the built-in
Where<T>(...)and (as others have already pointed out) theFirstOrDefault<T>(...)extension methods.Your code would then look like so:
The best you could get then, writing your own generic method, would be this:
And that is really just redundant. Especially when your calling code would be actually longer using the helper method:
And even worse, your code is no longer using a fluent, composable syntax. This just makes readability and maintenance more difficult.
If you stick with using the
IQueryable<T>extension methods then you can do composition like this:One very important thing to note here is that the
predicateparameter in theIQueryable<T>.Where<T>(...)extension method is of typeExpression<Func<T, bool>>. This allows theIQueryable<T>provider to construct the native SQL (or other native provider query) at the very last moment before returning a result.Not using
Expression<Func<T, bool>>means that your query would be the equivalent of this:And that would mean the query will load every record from the “PAC” table into memory before selecting the first filtered result and throwing out the rest of the results.
The bottom-line is that by making a generic helper method you are rewriting existing framework code and you open yourself to performance and maintenance issues while also reducing code readability.
I hope this helps.