public class GenericRepository<TEntity> where TEntity : class
{
internal DbContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository()
{
this.context = new EWEFDTO();
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
// Expression<Func<TEntity, bool>> orderBy = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "", int iOffset=0,int iMax=10)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
//return query.OrderBy(filter).ToList();
// return query.ToList();
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
query= orderBy(query);
}
if (iOffset > 0)
iOffset = iOffset * iMax;
if (iMax == 0)
iMax = 10;
if (orderBy != null)
return query.Skip(iOffset).Take(iMax).ToList();
else
return query.ToList();
// }
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual TEntity Insert(TEntity entity)
{
return dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
DeleteEntity(entityToDelete);
}
public virtual void DeleteEntity(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
//TEntity objTEntity = dbSet.Find(3);
//TEntity objNewEntity = (TEntity)ReflectionHelper.SetDTOValueFromEntity(objTEntity, entityToUpdate);
//context.Entry(objNewEntity);
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual int SaveChanges()
{
return context.SaveChanges();
}
}