|
using LinqKit; |
|
using System; |
|
using System.Collections.Generic; |
|
using System.Data.Entity; |
|
using System.Linq; |
|
using System.Linq.Expressions; |
|
|
|
public class EFRepository<T> : IRepository<T> where T : class |
|
{ |
|
protected DbContext Context; |
|
protected readonly DbSet<T> Table; |
|
|
|
public EFRepository(DbContext context) |
|
{ |
|
Context = context; |
|
Table = Context.Set<T>(); |
|
} |
|
|
|
public IEnumerable<T> Get(Expression<Func<T, bool>> searchCriteria = null) |
|
{ |
|
return searchCriteria == null ? Table.ToList() : Table.Where(searchCriteria).ToList(); |
|
} |
|
|
|
public ResultPage<T> GetByPage<TKey>(Expression<Func<T, bool>> searchCriteria, Expression<Func<T, TKey>> orderCriteria, bool orderDescending, int pageNumber, int recordsPerPage) |
|
{ |
|
// 1. Search for rows (AsExpandable used as sub-queries do not play nice with LINQ to SQL. See here: http://tomasp.net/blog/linq-expand.aspx |
|
var rawResults = searchCriteria == null ? Table : Table.AsExpandable().Where(searchCriteria); |
|
|
|
// 2. Apply ordering |
|
if (orderDescending) |
|
{ |
|
rawResults = rawResults.OrderByDescending(orderCriteria); |
|
} |
|
else |
|
{ |
|
rawResults = rawResults.OrderBy(orderCriteria); |
|
} |
|
|
|
// 3. Skip and take pages |
|
var resultingRows = rawResults.Skip((pageNumber - 1) * recordsPerPage).Take(recordsPerPage); |
|
|
|
// 4. Return results |
|
return new ResultPage<T>(resultingRows, rawResults.Count(), resultingRows.Count()); |
|
} |
|
|
|
public T GetByKey(object key) |
|
{ |
|
return Table.Find(key); |
|
} |
|
|
|
public virtual void Add(T record) |
|
{ |
|
Table.Add(record); |
|
} |
|
|
|
public virtual void AddMany(IEnumerable<T> records) |
|
{ |
|
Table.AddRange(records); |
|
} |
|
|
|
public virtual void Update(T record) |
|
{ |
|
Table.Attach(record); |
|
Context.Entry(record).State = EntityState.Modified; |
|
} |
|
|
|
public void Remove(object key) |
|
{ |
|
var record = Table.Find(key); |
|
Table.Remove(record); |
|
} |
|
|
|
public void RemoveMany(IEnumerable<T> records) |
|
{ |
|
Table.RemoveRange(records); |
|
} |
|
|
|
public void RemoveAll() |
|
{ |
|
Table.RemoveRange(Table); |
|
} |
|
|
|
public virtual void Commit() |
|
{ |
|
Context.SaveChanges(); |
|
} |
|
|
|
public int RowCount(Expression<Func<T, bool>> filterCriteria = null) |
|
{ |
|
if (filterCriteria == null) filterCriteria = t => true; |
|
return Table.Count(filterCriteria); |
|
} |
|
|
|
public void Dispose() |
|
{ |
|
Context.Dispose(); |
|
} |
|
} |