Last active
January 9, 2021 22:28
-
-
Save KaiserWerk/4ea7f3ed251f03fcd1ef0096276469d9 to your computer and use it in GitHub Desktop.
C# Repository pattern
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.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(); | |
} | |
} | |
} |
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.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