Question

In the generic repository described here, a single database context internal SchoolContext context; is used. I want to build a generic repository but because I am using multiple databases (multiple connection strings), I do not want to hard code the database context. Is there a way of doing this that does not require re-writing the same methods for a different database context?

Was it helpful?

Solution

Just make the context generic

Change the generic repository to look like that for example:

public class GenericRepository<TContext, TEntity>
    where TContext: DbContext
    where TEntity: class 
{
    internal TContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(TContext context) 
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

Now you can instantiate a repository for any kind of context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top