I have functions like this one below that loads a database table using LinqToSql and returns a list of the entries converted into my custom model class:
public List<AreaModel> LoadListOfAreaModels(Boolean includeDeleted = false)
{
using (LinqToSqlDataContext dc = new LinqToSqlDataContext())
{
IQueryable<Areas> filtered = includeDeleted
? dc.Areas.Where((c) => !c.DataRowDeleted)
: dc.Areas;
return filtered.Select((c) => AreaModel.ModelFactoryFromLinq(c)).ToList();
}
}
Now I have quite a few tables and all have to get loaded and converted in the same way.
Can I somehow avoid typing this function a dozen times and just changing the AreaModel and Areas to e.g. TownModel and Towns by using a generic function?
I already tried this, but failed because I could not find a way to call a static class method if I only have the generic type parameter of it.
Further info: All XxxModel classes have the common superclass ModelBase (which does not contain the static factory method I need to call though!), all Linq table classes (like Areas or Towns) implement the common interface ILinqClass.
Any ideas on how to implement this the most elegant way?
Inspired by knittl's answer, I came up with this solution:
public List<TModel> LoadListOfModels<TLinq, TModel>(
Func<TLinq, bool> filter,
Func<TLinq, TModel> modelFactory
)
where TLinq : class, ILinqClass
where TModel : ModelBase
{
using (LinqToSqlDataContext dc = new LinqToSqlDataContext())
{
return dc.GetTable<TLinq>()
.Where(filter)
.Select(modelFactory)
.ToList();
}
}
DataRowDeleteddefined inModelBase?DataRowDeletedit's part of an interfaceModelBaseimplements