Reputation: 16290
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?
Upvotes: 2
Views: 3525
Reputation: 2113
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
.
Upvotes: 4