/Gradebook.Data/Repository.cs
C# | 122 lines | 104 code | 18 blank | 0 comment | 15 complexity | 57ad81b4cb0c1db6b47ec08d8ae8298a MD5 | raw file
- using System;
- using System.Data;
- using System.Data.Entity;
- using System.Linq;
- using System.Linq.Expressions;
- using Gradebook.Contracts.Repositories;
-
- namespace Gradebook.Data
- {
- public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
- where TEntity : class
- {
- protected readonly DbContext DbContext;
- protected readonly DbSet<TEntity> DbSet;
-
- protected Repository(DbContext dbContext)
- {
- if (dbContext == null)
- throw new ArgumentNullException("dbContext");
-
- DbContext = dbContext;
- DbSet = DbContext.Set<TEntity>();
- }
-
- public virtual TEntity Read(TKey id)
- {
- return DbSet.Find(id);
- }
-
- public virtual bool TryRead(TKey id, out TEntity entity)
- {
- entity = DbSet.Find(id);
- return entity != null;
- }
-
- public virtual void Delete(TKey id)
- {
- var entity = Read(id);
- if (entity == null) throw new ArgumentException("id");
- var entityToDelete = DbSet.Find(id);
- Delete(entityToDelete);
- }
-
- public virtual void Create(TEntity entity)
- {
- DbSet.Add(entity);
- }
-
- public virtual void Delete(TEntity entity)
- {
- var dbEntityEntry = DbContext.Entry(entity);
- if (dbEntityEntry.State != EntityState.Deleted)
- {
- dbEntityEntry.State = EntityState.Deleted;
- }
- else
- {
- if (DbContext.Entry(entity).State == EntityState.Detached)
- {
- DbSet.Attach(entity);
- }
- DbSet.Remove(entity);
- }
- }
-
- public virtual void Update(TEntity entity)
- {
- var dbEntityEntry = DbContext.Entry(entity);
- if (dbEntityEntry.State == EntityState.Detached)
- {
- DbSet.Attach(entity);
- }
- DbContext.Entry(entity).State = EntityState.Modified;
- }
-
- public virtual IQueryable<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);
- }
-
- query = includeProperties
- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
- .Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
-
- return orderBy != null ? orderBy(query) : query;
- }
-
- public virtual IQueryable<TEntity> GetAll()
- {
- return DbSet;
- }
-
- public long Count()
- {
- return DbSet.Count();
- }
-
- public virtual bool Contains(TKey id)
- {
- return DbSet.Find(id) != null;
- }
- }
-
- public class Repository<TEntity> : Repository<TEntity, int>, IRepository<TEntity>
- where TEntity : class
- {
- public Repository(DbContext dbContext) : base(dbContext) { }
- }
-
- public class RepositoryBase<TEntity> : Repository<TEntity, object>, IRepositoryBase<TEntity>
- where TEntity : class
- {
- public RepositoryBase(DbContext dbContext) : base(dbContext) { }
- }
- }