Question

I am using NerdDinner (MVC 2) as the foundation of my project. While the repository interface design works very well, in my real world application there are a dozen of model classes (while NerdDinner has only one, Dinner), which means I need one interface (and its implementation) for each class. Additionally, the basic interface methods (get, save, add, delete etc) are the same, which means I have to copy & paste the same code in every implementation class. The only thing that changes is the type of the class, for example the Customer's interface exposes:

void Add(Customer customer)

and the Order's interface exposes:

void Add(Order order)

The implementation is essentially the same for both methods but uses the appropriate model type, of course:

db.Customers.InsertOnSubmit(customer)

and

db.Orders.InsertOnSubmit(order)

respectively. To stop repeating the same code over and over again (and minimize the number of .cs files in my project) I thought I could define a generic base repository interface, for example:

public interface IRepository<T>
{
void Add(T t)
void Delete(T t)
void Save();   // This one is truly the same in any case!
}

but how can I apply the generic type to the implementation code? I need something like:

db.T.InsertOnSubmit(t)

can this be done?

PS: db is the datacontext object (I am using the linq to sql designer).

Thanks

Was it helpful?

Solution

From your question

but how can I apply the generic type to the implementation code? I need something like:
db.T.InsertOnSubmit(t)
can this be done?

I am assuming you need something like this

db.GetTable<T>().InsertOnSubmit(entity);

A simple repository implementation to give you an idea:

public class Repository<T> : IRepository<T> where T : class
{
    private NorthwindDataContext db = new NorthwindDataContext();

    public Table<T> Data
    {
        get
        {
            return db.GetTable<T>();
        }
    }

    public void Add(T entity)
    {
        db.GetTable<T>().InsertOnSubmit(entity);
    }

    public void Delete(T entity)
    {
        db.GetTable<T>().DeleteOnSubmit(entity);
    }

    public void Save()
    {
        db.SubmitChanges();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top