Created
December 20, 2016 18:38
-
-
Save camarin24/f1b50cc7e5aeefe4c83b27b0882a8f7d to your computer and use it in GitHub Desktop.
BaseDbContextManager
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<T> where T : class | |
{ | |
IQueryable<T> All { get; } | |
T Delete(T entity); | |
T FindById(object Id); | |
T Insert(T entity); | |
T Update(T entity, T oldEntity, out bool modified); | |
} | |
public abstract class BaseEFRepository<TEntity> : IRepository<TEntity> where TEntity : class, new() | |
{ | |
private IRepositoryValidator<TEntity> _validator = null; | |
protected Entities _entities; | |
protected DbSet<TEntity> _dbSet; | |
public BaseEFRepository(Entities entities) | |
{ | |
this._entities = entities; | |
this._dbSet = entities.Set<TEntity>(); | |
} | |
public BaseEFRepository(Entities entities, IRepositoryValidator<TEntity> validator) | |
{ | |
this._entities = entities; | |
this._dbSet = entities.Set<TEntity>(); | |
this._validator = validator; | |
} | |
public IQueryable<TEntity> All | |
{ | |
get { return _dbSet; } | |
} | |
public virtual TEntity Insert(TEntity entity) | |
{ | |
if (_validator != null) | |
{ | |
_validator.ValidatePreInsert(entity); | |
} | |
_dbSet.Add(entity); | |
return entity; | |
} | |
public virtual TEntity Delete(TEntity entity) | |
{ | |
if (_validator != null) | |
{ | |
_validator.ValidatePreDelete(entity); | |
} | |
_dbSet.Remove(entity); | |
return entity; | |
} | |
public virtual TEntity Update(TEntity editedEntity, TEntity originalEntity, out bool changed) | |
{ | |
_entities.Entry(originalEntity).CurrentValues.SetValues(editedEntity); | |
if (_validator != null) | |
{ | |
_validator.ValidatePreUpdate(originalEntity); | |
} | |
changed = _entities.Entry(originalEntity).State == System.Data.Entity.EntityState.Modified; | |
return originalEntity; | |
} | |
public virtual TEntity FindById(object id) | |
{ | |
var newId = CastPrimaryKey(id); | |
return _dbSet.Find(newId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment