Last active
November 8, 2022 00:53
-
-
Save davidbreyer/9515932 to your computer and use it in GitHub Desktop.
Generic Repository Pattern for Entity Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Generic Repository Pattern for Entity Framework | |
//http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle | |
public abstract class GenericRepository<C, T> : | |
IDisposable, IGenericRepository<T> where T : class where C : DbContext, new() { | |
private C _entities = new C(); | |
public C Context { | |
get { return _entities; } | |
set { _entities = value; } | |
} | |
public virtual IQueryable<T> GetAll() { | |
IQueryable<T> query = _entities.Set<T>(); | |
return query; | |
} | |
public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate) { | |
IQueryable<T> query = _entities.Set<T>().Where(predicate); | |
return query; | |
} | |
public virtual void Add(T entity) { | |
_entities.Set<T>().Add(entity); | |
} | |
public virtual void Delete(T entity) { | |
_entities.Set<T>().Remove(entity); | |
} | |
public virtual void Edit(T entity) { | |
_entities.Entry(entity).State = System.Data.Entity.EntityState.Modified; | |
} | |
public virtual void Save() { | |
_entities.SaveChanges(); | |
} | |
//Implementing IDisposable correctly http://msdn.microsoft.com/en-us/library/ms244737.aspx | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
// The bulk of the clean-up code is implemented in Dispose(bool) | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposing) | |
{ | |
_entities.Dispose(); | |
} | |
} | |
} | |
public interface IGenericRepository<T> where T : class | |
{ | |
IQueryable<T> GetAll(); | |
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate); | |
void Add(T entity); | |
void Delete(T entity); | |
void Edit(T entity); | |
void Save(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment