Skip to content

Instantly share code, notes, and snippets.

@KaiserWerk
Last active January 9, 2021 22:28
Show Gist options
  • Save KaiserWerk/4ea7f3ed251f03fcd1ef0096276469d9 to your computer and use it in GitHub Desktop.
Save KaiserWerk/4ea7f3ed251f03fcd1ef0096276469d9 to your computer and use it in GitHub Desktop.
C# Repository pattern
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Core.Repositories
{
public abstract class GenericRepository<T> : IRepository<T> where T : class
{
protected MyDbContext context;
public GenericRepository(MyDbContext ctx)
{
this.context = ctx;
}
public virtual T Get(int id)
{
return this.context.Find<T>(id);
}
public virtual IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return this.context.Set<T>().AsQueryable().Where(predicate);
}
public virtual IEnumerable<T> GetAll()
{
return this.context.Set<T>().ToList();
}
public virtual void Add(T obj)
{
this.context.Set<T>().Add(obj);
}
public virtual void Edit(T obj)
{
this.context.Update(obj);
}
public virtual void Remove(T obj)
{
this.context.Remove(obj);
}
public virtual void SaveChanges()
{
this.context.SaveChanges();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Core.Repositories
{
public interface IRepository<T>
{
T Get(int id);
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
IEnumerable<T> GetAll();
void Add(T obj);
void Edit(T obj);
void Remove(T obj);
void SaveChanges();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment