Created
July 19, 2012 14:40
-
-
Save johnpapa/3144387 to your computer and use it in GitHub Desktop.
EF Repository Foundations
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
public class EFRepository<T> : IRepository<T> where T : class | |
{ | |
public EFRepository(DbContext dbContext) | |
{ | |
if (dbContext == null) | |
throw new ArgumentNullException("dbContext"); | |
DbContext = dbContext; | |
DbSet = DbContext.Set<T>(); | |
} | |
protected DbContext DbContext { get; set; } | |
protected DbSet<T> DbSet { get; set; } | |
public virtual IQueryable<T> GetAll() | |
{ | |
return DbSet; | |
} | |
public virtual T GetById(int id) | |
{ | |
return DbSet.FirstOrDefault(PredicateBuilder.GetByIdPredicate<T>(id)); | |
} | |
public virtual void Add(T entity) | |
{ | |
DbEntityEntry dbEntityEntry = DbContext.Entry(entity); | |
if (dbEntityEntry.State != EntityState.Detached) | |
{ | |
dbEntityEntry.State = EntityState.Added; | |
} | |
else | |
{ | |
DbSet.Add(entity); | |
} | |
} | |
public virtual void Update(T entity) | |
{ | |
DbEntityEntry dbEntityEntry = DbContext.Entry(entity); | |
if (dbEntityEntry.State == EntityState.Detached) | |
{ | |
DbSet.Attach(entity); | |
} | |
dbEntityEntry.State = EntityState.Modified; | |
} | |
public virtual void Delete(T entity) | |
{ | |
DbEntityEntry dbEntityEntry = DbContext.Entry(entity); | |
if (dbEntityEntry.State != EntityState.Deleted) | |
{ | |
dbEntityEntry.State = EntityState.Deleted; | |
} | |
else | |
{ | |
DbSet.Attach(entity); | |
DbSet.Remove(entity); | |
} | |
} | |
public virtual void Delete(int id) | |
{ | |
var entity = GetById(id); | |
if (entity == null) return; // not found; assume already deleted. | |
Delete(entity); | |
} | |
} |
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
public interface IRepository<T> where T : class | |
{ | |
IQueryable<T> GetAll(); | |
T GetById(int id); | |
void Add(T entity); | |
void Update(T entity); | |
void Delete(T entity); | |
void Delete(int id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment