using DataStoring.Contract; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace DataStoring.EfCore { public class Repository : IRepository where TEntity : class { private readonly DPContext _db; public IQueryable Query => _db.Set(); public Repository(DPContext db) { _db = db; } public void Delete(int id) { try { var entity = _db.Set().Find(id); if(entity == null) { throw new Exception("Id not found"); } } catch(Exception e) { throw new Exception(string.Format("Cant delete entity with id {0} # {1} " ,id,e.Message)); } } public void Insert(TEntity entity) { _db.Set().Add(entity); _db.SaveChanges(); } public void Update(TEntity entity) { _db.Entry(entity).State = EntityState.Modified; _db.SaveChanges(); } public IQueryable Get(Expression> filter = null, Func, IOrderedQueryable> orderBy = null, string includeProperties = "") { IQueryable query = _db.Set(); if(filter != null) query = query.Where(filter); if(includeProperties != null) { foreach(var includeProperty in includeProperties.Split( new char[] {','}, StringSplitOptions.RemoveEmptyEntries )) query = query.Include(includeProperty); } if(orderBy != null) { return orderBy(query); } else { return query; } } } }