Last active
January 10, 2025 04:05
-
-
Save vkobel/5501260 to your computer and use it in GitHub Desktop.
Generic C# .NET Repository pattern (interface + implementation)
This file contains hidden or 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
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(); | |
} | |
} |
This file contains hidden or 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
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great Example!