Created
October 13, 2014 10:34
-
-
Save stevenh77/10c0491bf65abc16bd93 to your computer and use it in GitHub Desktop.
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 abstract class DataRepositoryBase<T, U> : IDataRepository<T> | |
where T : class, IIdentifiableEntity, new() | |
where U : DbContext, new() | |
{ | |
protected abstract T AddEntity(U entityContext, T entity); | |
protected abstract T UpdateEntity(U entityContext, T entity); | |
protected abstract IEnumerable<T> GetEntities(U entityContext); | |
protected abstract T GetEntity(U entityContext, int id); | |
public T Add(T entity) | |
{ | |
using (U entityContext = new U()) | |
{ | |
T addedEntity = AddEntity(entityContext, entity); | |
entityContext.SaveChanges(); | |
return addedEntity; | |
} | |
} | |
public void Remove(T entity) | |
{ | |
using (U entityContext = new U()) | |
{ | |
entityContext.Entry<T>(entity).State = EntityState.Deleted; | |
entityContext.SaveChanges(); | |
} | |
} | |
public void Remove(int id) | |
{ | |
using (U entityContext = new U()) | |
{ | |
T entity = GetEntity(entityContext, id); | |
entityContext.Entry<T>(entity).State = EntityState.Deleted; | |
entityContext.SaveChanges(); | |
} | |
} | |
public T Update(T entity) | |
{ | |
using (U entityContext = new U()) | |
{ | |
T existingEntity = UpdateEntity(entityContext, entity); | |
SimpleMapper.PropertyMap(entity, existingEntity); | |
entityContext.SaveChanges(); | |
return existingEntity; | |
} | |
} | |
public IEnumerable<T> Get() | |
{ | |
using (U entityContext = new U()) | |
return (GetEntities(entityContext)).ToArray().ToList(); | |
} | |
public T Get(int id) | |
{ | |
using (U entityContext = new U()) | |
return GetEntity(entityContext, id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment