I have more DbContext's. I want to use just one GenericRepository. I try to create a GenericDbContextFactory. But how can I create TContext? What do I have to do, so the context is not null?
public class GenericRepository<TTable, TContext> : IGenericRepository<TTable, TContext>
where TTable : class
where TContext : DbContext
{
private TContext _context { get; set; } = default!;
private IGenericDbContextFactory _contextFactory;
private DbSet<TTable> _table { get; set; } = default!;
private readonly string _connectionString;
public GenericRepository(IGenericDbContextFactory contextFactory, string connectionString)
{
_connectionString = connectionString;
_contextFactory = contextFactory;
_context = GetNew();
}
public virtual void Reset()
{
_context.Dispose();
_context = GetNew();
}
public TContext GetNew()
{
var context = _contextFactory.Create(_connectionString) as TContext;
_table = context.Set<TTable>();
return context;
}
public async Task Save()
{
try
{
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
Reset();
throw new Exception(ex.Message);
}
_context.ChangeTracker.Clear();
}
public class GenericDbContextFactory : IGenericDbContextFactory
{
public DbContext Create(string connectionString)
{
if (!string.IsNullOrEmpty(connectionString))
{
var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
optionsBuilder.UseSqlServer(connectionString);
var context = new DbContext(optionsBuilder.Options);
return context;
}
else
{
throw new ArgumentNullException("ConnectionId");
}
}
}