HorseKing
HorseKing

Reputation: 454

Entity Framework, generic List

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();
    }

Upvotes: 1

Views: 1795

Answers (3)

swannee
swannee

Reputation: 3466

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:

public IQueryable<T> GetQueryable<T>()
{
   //Implementation depends on your data provider
   //return dataContext.GetTable<T>();
   //return session.Query<T>();
}

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.

public abstract class RepositoryBase<T>
{
   public IQueryable<T> GetQuery()
   {
     //Implementation determined by provider
    }

}

Upvotes: 1

DamienG
DamienG

Reputation: 6665

There already exists the method you want on DbContext called Set, e.g. var results = dbContext.Set();

If you are using ObjectContext then the method you want is CreateObjectSet().

Upvotes: 0

AjayK
AjayK

Reputation: 443

As there are no details in the question regarding what you have written already. If you just want to GET ALL RECORDS from the tables...Why LINQ...?? You can simply query the database using Data-set and Data-adapter in a method and to make that generic you just pass the table name and get back a Data-set, after that you can play with that Data-set as you like. Please elaborate more if there is any specific complexity in this case which I am missing.

Upvotes: 0

Related Questions