2

In the following class, how can I add the DBContext as a generic type parameter:

public abstract class Repository<T> : IRepository<T> where T : class
{
    private MyDBContext dataContext;
    private readonly IDbSet<T> dbset;

    protected Repository(IDatabaseFactory databaseFactory)
    {
        DatabaseFactory = databaseFactory;
        dbset = DataContext.Set<T>();
    }

    protected IDatabaseFactory DatabaseFactory
    {
        get;
        private set;
    }

    protected MyDBContext DataContext
    {
        get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
    }

    public virtual void Add(T entity)
    {
        dbset.Add(entity);
    }

    public virtual void Update(T entity)
    {
        dbset.Attach(entity);
        dataContext.Entry(entity).State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
        dbset.Remove(entity);
    }
}

Something in the lines of:

public abstract class Repository<C, T> : IRepository<T> where T

Would it work and how would the implementation be?

1
  • You already use T for entity, you are not constrained to the letter T, you can name them like TEntity and TDataContext Commented Nov 26, 2013 at 9:15

1 Answer 1

4

You mean like this?

public abstract class Repository<TContext, TEntity> : IRepository<TContext, TSet>
    where TContext : DbContext
    where TEntity : class
{
    private TContext context;
    private readonly IDbSet<TEntity>;

    // ...
}

Basically just replace every reference to MyDBContext with TContext.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to do that before, but I get an error on the line: 'get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }'
That's presumably because DatabaseFactory.Get() is returning something that can't be assigned to a DbContext variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.