112 lines
2.9 KiB
C#
112 lines
2.9 KiB
C#
using KanSan.DataStoring.Contract;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Linq.Expressions;
|
|
using System.Text;
|
|
|
|
namespace DataStoring.EF
|
|
{
|
|
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
|
|
{
|
|
private readonly KanSanContext _db;
|
|
private readonly DbSet<TEntity> dbSet;
|
|
|
|
public IQueryable<TEntity> Query => dbSet;
|
|
|
|
public Repository(KanSanContext db)
|
|
{
|
|
_db = db;
|
|
this.dbSet = db.Set<TEntity>();
|
|
}
|
|
public virtual void Delete(TEntity entityToDelete)
|
|
{
|
|
if (_db.Entry(entityToDelete).State == EntityState.Detached)
|
|
dbSet.Attach(entityToDelete);
|
|
dbSet.Remove(entityToDelete);
|
|
}
|
|
|
|
public void Delete(int id)
|
|
{
|
|
try
|
|
{
|
|
var entity = _db.Set<TEntity>().Find(id);
|
|
if(entity == null)
|
|
{
|
|
throw new Exception("Id not found");
|
|
}
|
|
}
|
|
catch(Exception e)
|
|
{
|
|
throw new Exception("Cant delete id");
|
|
}
|
|
|
|
}
|
|
|
|
public IEnumerable<TEntity> GetAll(string include)
|
|
{
|
|
return dbSet.Include(include);
|
|
}
|
|
|
|
public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")
|
|
{
|
|
IQueryable<TEntity> query = dbSet;
|
|
|
|
|
|
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).ToList();
|
|
}
|
|
else
|
|
{
|
|
return query.ToList();
|
|
}
|
|
}
|
|
|
|
public TEntity GetByID(object id)
|
|
{
|
|
return dbSet.Find(id);
|
|
}
|
|
|
|
public virtual void Insert(TEntity entity)
|
|
{
|
|
_db.Set<TEntity>().Add(entity);
|
|
_db.SaveChanges();
|
|
|
|
}
|
|
|
|
public IQueryable<TEntity> Include(params Expression<Func<TEntity, object>>[] includeExpressions)
|
|
{
|
|
IQueryable<TEntity> query = null;
|
|
foreach (var include in includeExpressions)
|
|
{
|
|
query = dbSet.Include(include);
|
|
}
|
|
return query ?? dbSet;
|
|
}
|
|
|
|
public void Update(TEntity entity)
|
|
{
|
|
_db.Entry(entity).State = EntityState.Modified;
|
|
_db.SaveChanges();
|
|
}
|
|
}
|
|
}
|