I have a question about generic list.
Assume that I have a database which contains three tables, User table, Order table and Item table.
In the C# code, I want a function, called GetList to get all he records from one of the three tables.
If I don’t use generic method, I have to create 3 different methods which looks like GetAllUsers(), GetAllOrders() and GetAllItems(). Inside these 3 methods, I will have to write the linq to query the database.
My question is how do I implement a generic method.
I want to use EF 4.1. I know how to do it by using NHibrate tho.
UPDATE
What about this? I found it from another post, it can be used to get one single record
public T GetSingleEntity<T>(Expression<Func<T,bool>> expression) where T:class
{
using (PersonalLinksEntities dbContext = new PersonalLinksEntities())
{
return dbContext.CreateObjectSet<T>().SingleOrDefault(expression);
}
}
PersonalLinksEntities is generated by EF, it is database first model.
Here is how I call this method
public ActionResult Index()
{
var thisOne = base.GetSingleEntity<PersonalRecord>(r=>r.RecordID==1);
return View();
}
The specific implementation going to depend on what you are using to access your data. NHib, EF, L2S? These all have some way of accessing an IQueryable generically.
You could expose a method such as:
But probably what you want to do is follow a repository pattern with a different repository for each type. But you can use an abstract base repository that accepts a type parameter and is reusable.