Lee
Lee

Reputation: 3969

Trouble fully abstracting data access method

I'm abstracting my data access layer in to a centralised generic abstract class so that my other type specific classes can just call the generic methods without defining implementation.

public abstract class _DALMethods<T>
{
    public virtual List<T> GetAll()
    {
        List<T> ents = new List<T>();

        using (var db = new Entities())
        {
            ents = db.tblEmployees.ToList();
        }

        return ents;
    }

    public virtual void Add(T obj)
    {
        using (var db = new Entities())
        {
            db.tblEmployees.Add(obj);
            db.SaveChanges();
        }
    }
}

My problem is how to "generic-ise" the very specific call to the employee table DbSet list, especially when it requires the instantiation of the EF entities.

using (var db = new Entities())
{
    ents = db.tblEmployees.ToList();
}

EDIT: I added another method to the abstract class that I will be using. How would I do the same for this?

Upvotes: 1

Views: 89

Answers (3)

Matt Whetton
Matt Whetton

Reputation: 6786

Sounds like you're asking a couple of questions. Firstly, if you want the Entities constructor part to be generic, you'll have to add a generic parameter to you class, maybe like this:

public abstract class _DALMethods<TEntities, T> where TEntities : DbContext, new() where T: class

Then you can call:

using (var db = new TEntities())

Secondly, to get the entities generically you can use

db.Set<T>().ToList();

Which will return all entities from the DbSet

For your add method, something like this should help:

Replace

db.tblEmployees.Add(obj);

with

db.Entry(obj).State = EntityState.Added;

Upvotes: 1

simon at rcl
simon at rcl

Reputation: 7344

Looks like this might work:

List<T> ents = new List<T>();

using (var db = new Entities())
{
    //ents = db.Set<T>().ToList(T);
    // correction due to Kyle and Lee below
    ents = db.Set<T>().ToList<T>();
}

return ents;

(I'm using EF 6). The Set<T> returns a DbSet<T>.

Cheers -

Upvotes: 3

Fede
Fede

Reputation: 44038

Seems like you're looking for the DbContext.Set<T>() method:

public virtual List<T> GetAll()
{
    using (var db = new Entities())
    {
        return db.Set<T>().ToList();
    }
}

then:

var dal = new _DALMethods<Employee>();
var employees = dal.GetAll(); // returns a List<Employee>

Upvotes: 3

Related Questions