This Repository < T > class in the FreeWebApplication.Repository namespace is an implementation of the IRepository < T > interface.It provides generic CRUD operations for entities of type T using Entity Framework Core.Let's go through its key components
using FreeWebApplication.DataBase;
using
Microsoft.EntityFrameworkCore;
namespace FreeWebApplication.Repository {
public class Repository<T> : IRepository < T > where T: class {
protected readonly APPDBContext _context;
private DbSet<T> _dbSet;
public Repository(APPDBContext
context) {
_context =
context;
_dbSet =
context.Set < T > ();
}
public int Count =>
_dbSet.Count();
public virtual IEnumerable<T>
List(QueryOptions<T> options) => BuildQuery(options).ToList();
public virtual T ? Get(int id)
=> _dbSet.Find(id);
public virtual T ?
Get(string id) => _dbSet.Find(id);
public virtual T ?
Get(QueryOptions < T > options) =>
BuildQuery(options).FirstOrDefault();
public virtual void Insert(T entity) =>
_dbSet.Add(entity);
public virtual void Update(T entity) =>
_context.Entry(entity).State = EntityState.Modified;
public virtual void Delete(T entity) =>
_dbSet.Remove(entity);
public virtual void Save() =>
_context.SaveChanges();
private IQueryable
< T > BuildQuery(QueryOptions < T > options)
{
IQueryable < T
> query = _dbSet;
foreach(string
include in options.GetIncludes())
{
query =
query.Include(include);
}
if
(options.HasWhere) {
query =
query.Where(options.Where);
}
if (options.HasOrderBy) {
if (options.OrderByDirection ==
"asc")
query =
query.OrderBy(options.OrderBy);
else
query =
query.OrderByDescending(options.OrderBy);
}
if (options.HasPaging)
{
query =
query.PageBy(options.PageNumber, options.PageSize);
}
return query;
}
}
}