Created
December 4, 2013 06:11
-
-
Save JulienSansot/7783122 to your computer and use it in GitHub Desktop.
Entity Framework Generic Repository
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
public interface IRepository | |
{ | |
IQueryable<T> Query<T>() where T : class; | |
T Add<T>(T entity) where T : class; | |
T Update<T>(T entity) where T : class; | |
void Delete<T>(T entity) where T : class; | |
} | |
public class Repository : IRepository | |
{ | |
private readonly DbContext _context; | |
public Repository(DbContext context) | |
{ | |
_context = context; | |
} | |
public IQueryable<T> Query<T>() where T : class | |
{ | |
return _context.Set<T>().AsQueryable().AsNoTracking(); | |
} | |
public T Add<T>(T entity) where T : class | |
{ | |
_context.Entry(entity).State = System.Data.EntityState.Added; | |
Save(); | |
return entity; | |
} | |
public T Update<T>(T entity) where T : class | |
{ | |
_context.Entry(entity).State = System.Data.EntityState.Modified; | |
Save(); | |
return entity; | |
} | |
public void Delete<T>(T entity) where T : class | |
{ | |
_context.Entry(entity).State = System.Data.EntityState.Deleted; | |
Save(); | |
} | |
private void Save() | |
{ | |
_context.SaveChanges(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment