T variable
public class GenericRepository<T> where T : class
{
private readonly DbContext _context; // Connect database
public GenericRepository(DbContext context)
{
_context = context;
}
public IQueryable<T> GetAll() // All records of type T are returned as a query
{
return _context.Set<T>(); // Accessing table T in DbContext
}
}
Product table
// Product table
var productRepo = new GenericRepository<Product>(dbContext);
var products = productRepo.GetAll()
.Where(p => p.Name.Contains("abc"))
.ToList();
Customer table
// Customer Table
var customerRepo = new GenericRepository<Customer>(dbContext);
var customers = customerRepo.GetAll()
.Where(c => c.City == "İstanbul")
.ToList();
Result
public class GenericRepository<T> where T : class
{
private readonly DbContext _context; // Connect database
public GenericRepository(DbContext context)
{
_context = context;
}
public IQueryable<T> GetAll() // All records of type T are returned as a query
{
return _context.Set<T>(); // Accessing table T in DbContext
}
}
// Product table
var productRepo = new GenericRepository<Product>(dbContext);
var products = productRepo.GetAll()
.Where(p => p.Name.Contains("abc"))
.ToList();
Customer table
// Customer Table
var customerRepo = new GenericRepository<Customer>(dbContext);
var customers = customerRepo.GetAll()
.Where(c => c.City == "İstanbul")
.ToList();
Result
// Customer Table
var customerRepo = new GenericRepository<Customer>(dbContext);
var customers = customerRepo.GetAll()
.Where(c => c.City == "İstanbul")
.ToList();
The same GetAll() method works for both Product and Customer because the type T is determined when that repository instance is created.