Skip to content

Instantly share code, notes, and snippets.

@vkobel
Last active December 7, 2023 14:16
Show Gist options
  • Save vkobel/5501260 to your computer and use it in GitHub Desktop.
Save vkobel/5501260 to your computer and use it in GitHub Desktop.
Generic C# .NET Repository pattern (interface + implementation)
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Data.GenericRepo {
public interface IRepository<T> : IDisposable where T : class {
T[] GetAll();
IQueryable<T> Query(Expression<Func<T, bool>> predicate);
T GetSingle(Expression<Func<T, bool>> predicate);
void Create(T entity);
void Add(T entity);
void Delete(T entity);
int Persist();
}
}
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Data.GenericRepo {
/// <summary>
/// Build a repository for a specified POCO class and a DbContext
/// </summary>
/// <typeparam name="T">The entity to be accessed, must be present in the DbContext</typeparam>
public class Repository<T> : IRepository<T> where T: class {
private DbContext ctx;
private DbSet<T> entities;
public DbSet<T> Entities {
get { return entities; }
}
public Repository(DbContext ctx) {
this.ctx = ctx;
entities = ctx.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Single(p => p.PropertyType == typeof(DbSet<T>))
.GetValue(ctx) as DbSet<T>;
}
#region repo methods
public T[] GetAll() {
return entities.ToArray();
}
public IQueryable<T> Query(Expression<Func<T, bool>> predicate) {
return entities.Where(predicate);
}
public T GetSingle(Expression<Func<T, bool>> predicate) {
return entities.SingleOrDefault(predicate);
}
public void Create(T entity) {
Add(entity);
Persist();
}
public void Add(T entity) {
entities.Add(entity);
}
public void Delete(T entity) {
entities.Remove(entity);
}
public int Persist() {
return ctx.SaveChanges();
}
#endregion
public void Dispose() {
if(ctx != null) {
ctx.Dispose();
ctx = null;
}
GC.SuppressFinalize(this);
}
}
}
@CecoiPavel
Copy link

Great Example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment