using KanSan.Base.Interfaces; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; namespace KanSan.Base { public class BaseRepository : IRepository where TEntity : class { internal KanSanContext context; internal DbSet dbSet; public BaseRepository(KanSanContext context) { this.context = context; if (context == null) throw new ArgumentNullException("context"); this.dbSet = context.Set(); } public virtual void Delete(TEntity entityToDelete) { if (context.Entry(entityToDelete).State == EntityState.Detached) dbSet.Attach(entityToDelete); dbSet.Remove(entityToDelete); } public void Delete(object id) { TEntity entityToDelete = dbSet.Find(id); Delete(entityToDelete); } public IEnumerable Get(Expression> filter = null, Func, IOrderedQueryable> orderBy = null, string includeProperties = "") { IQueryable 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) { dbSet.Add(entity); } public void Update(TEntity entityToUpdate) { dbSet.Attach(entityToUpdate); IDatabaseEntry x = (entityToUpdate as IDatabaseEntry); if(x == null) return; if(x.ID.Equals(0)) { // Scheint ein neuer Eintrag zu sein context.Entry(entityToUpdate).State = EntityState.Added; } else { context.Entry(entityToUpdate).State = EntityState.Modified; } } } }