using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Contextlib { public class GenericRepository where T : class { private DbContext Context { get; set; } private DbSet Set { get; set; } public GenericRepository(DbContext context) { Context = context; Set = Context.Set(); } public virtual T? GetById(object id) => Set.Find(id); public virtual T? GetById(object id, Expression>? filter = null, params string[] includeProperties) { IQueryable query = Set; if (filter != null) { query = query.Where(filter); } foreach (string includeProperty in includeProperties) { query = query.Include(includeProperty); } return query.FirstOrDefault(); } public virtual IEnumerable GetItems(Expression>? filter = null, int index = 0, int count = 10, params string[] includeProperties) => GetItems(filter, null, index, count, includeProperties); public virtual IEnumerable GetItems(Func, IOrderedQueryable>? orderBy = null, int index = 0, int count = 10, params string[] includeProperties) => GetItems(null, orderBy, index, count, includeProperties); public virtual IEnumerable GetItems(int index = 0, int count = 10, params string[] includeProperties) => GetItems(null, null, index, count, includeProperties); public virtual IEnumerable GetItems(Expression>? filter = null, Func, IOrderedQueryable>? orderBy = null, int index = 0, int count = 10, params string[] includeProperties) { IQueryable query = Set; if (filter != null) { query = query.Where(filter); } foreach (string includeProperty in includeProperties) { query = query.Include(includeProperty); } if (orderBy != null) { query = orderBy(query); } return query.Skip(index * count) .Take(count) .ToList(); } public virtual void Insert(T entity) { if (Set.Entry(entity).IsKeySet) return; Set.Add(entity); } public virtual void Insert(params T[] entities) { foreach (var entity in entities) { Insert(entity); } } public virtual void Delete(object id) { T? entity = Set.Find(id); if (entity == null) return; Delete(entity); } public virtual void Delete(T entity) { if (Context.Entry(entity).State == EntityState.Detached) { Set.Attach(entity); } Set.Remove(entity); } public virtual void Update(T entity) { Set.Attach(entity); Context.Entry(entity).State = EntityState.Modified; } public virtual int Count() { return Set.Count(); } } }