views:

38

answers:

3

I am trying to create a generic base repository for my Linq2Sql entities. I'd like to implement a generic FindAll() method like so.

class BaseRepository<T> : IBaseRepository<T>
{
    private readonly FooDataContext _ctx = new FooDataContext();

    public IQueryable<T> FindAll()
    {
        return _ctx.T;
    }

    public void Add(T entity)
    {
        _ctx.T.InsertOnSubmit(entity);
    }

    public void Save()
    {
        _ctx.SubmitChanges();
    }
}

Is there any way to do this without having to use reflection and create slowdown that would make it virtually worthless?

A: 

If you use an in-memory storage system to cache the reflected attributes of a specific type after the first use, you may not have a "virtually worthless" situation at all. In fact, without testing it, you don't really know that the reflection solution would be a problem, do you? (Much of .NET uses reflection and people don't see slowdown in those scenarios. Serialization is one of them.)

John Fisher
A: 

This should work:

public IQueryable<T> FindAll()
{
    return _ctx.GetTable<T>();
}
Lee
+2  A: 

DataContext has what you need in it already.

public IQueryable<T> FindAll()
{
    return _ctx.GetTable<T>();
}

public void Add(T entity)
{
    _ctx.GetTable<T>().InsertOnSubmit(entity);
}
Justin Rudd
This is perfect, thanks. You get the check-mark for being more verbose, and you need the points more than Lee =)
jcm
Thanks! My quest to break a 1000 is getting closer and closer!
Justin Rudd