public class Repository : IRepository
{
private ApplicationContext _context;
public Repository(ApplicationContext context)
{
_context = context;
}
public IQueryable<TEntity> Query<TEntity>() where TEntity : class
{
var _dbSet = _context.Set<TEntity>();
return _dbSet.AsNoTracking();
}
public TEntity Get<TEntity>(int id) where TEntity : class
{
var _dbSet = _context.Set<TEntity>();
return _dbSet.Find(id);
}
public void Create<TEntity>(TEntity item) where TEntity : class
{
var _dbSet = _context.Set<TEntity>();
_dbSet.Add(item);
_context.SaveChanges();
}
public void Update<TEntity>(TEntity item) where TEntity : class
{
var _dbSet = _context.Set<TEntity>();
_dbSet.Attach(item);
_context.Entry(item).State = EntityState.Modified;
_context.SaveChanges();
}
public void Remove<TEntity>(int id) where TEntity : class
{
var _dbSet = _context.Set<TEntity>();
var item = _dbSet.Find(id);
_dbSet.Remove(item);
_context.SaveChanges();
}
}
Context:
public class ApplicationContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { }
}
Register context in DI
services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connectionString));
My solution in repository:
Context:
Register context in DI
services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connectionString));