In my project, I have 2 Entity objects (delegate for 2 tables in db) as below:
- Tbl_Person {ID, Name}
- Tbl_Class {ID, Name, PersonID}
In DAL, I create 2 classes for these Entities, and write function GetList():
– Class Person:
public List<Tbl_Person> GetList()
{
using (var db = DatabaseHelper.DataContext())
{
try
{
var _t = (from info in db.**tbPerson**
select info).ToList();
return _t.ToList<**Tbl_Person**>();
}
catch (Exception ex)
{
throw ex;
}
}
}
Class MyClass:
public List<Tbl_Class> GetList()
{
using (var db = DatabaseHelper.DataContext())
{
try
{
var _t = (from info in db.**tbClass**
select info).ToList();
return _t.ToList<**Tbl_Class**>();
}
catch (Exception ex)
{
throw ex;
}
}
}
If I use 2 classes, I can use GetList() to get list object correctly.
But it seems we have duplicate function GetList() here. What I want just is only 1 function GetList() like this:
public List<T> GetList()
{
using (var db = DatabaseHelper.DataContext())
{
try
{
var _t = (from info in db.**????????**
select info).ToList();
return _t.ToList<**T**>();
}
catch (Exception ex)
{
throw ex;
}
}
}
Firstly, get rid of the pointless try/catch blocks. Each of those methods is twice as long as it needs to be, because you’re catching exceptions and just rethrowing them – but losing information at the same time! (If you must rethrow, use just
throw;instead ofthrow ex;.)Secondly, there’s absolutely no point in using a query expression here. You’re just interested in the whole table. (Are you sure you want to fetch the whole table on each call, by the way?)
Thirdly, assuming these are proper strongly-typed data contexts, I wouldn’t expect you to have to specify the type argument for
ToListin the first place.So your two methods can *actually be reduced to:
Now you could remove the redundancy here using
DataContext.GetTable<TEntity>:It’s not really clear whether you need the methods in the individual classes…
(In addition to all of this, I’d strongly encourage you to rename your types to remove the
Tbl_prefix from the mapping. It looks pretty horrible in code, IMO.)