Skip to content

Instantly share code, notes, and snippets.

@odytrice
Last active October 26, 2016 10:57
Show Gist options
  • Save odytrice/5925782 to your computer and use it in GitHub Desktop.
Save odytrice/5925782 to your computer and use it in GitHub Desktop.
A Generic DataRepository Class that Abstracts the DbContext
public class DataRepository : IDataRepository
{
private DbContext _dbContext;
public DataRepository(DbContext context)
{
_dbContext = context;
}
public IQueryable<T> Query<T>() where T : class
{
return _dbContext.Set<T>();
}
public IQueryable<T> Query<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
{
IQueryable<T> query = Query<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public T GetByID<T>(int id) where T : class
{
return _dbContext.Set<T>().Find(id);
}
public void Add<T>(T item) where T : class
{
_dbContext.Set<T>().Add(item);
}
public void Delete<T>(T item) where T : class
{
_dbContext.Set<T>().Remove(item);
}
public void Update<T>(T entity) where T : class
{
if (_dbContext.Entry(entity).State == EntityState.Detached)
{
_dbContext.Set<T>().Attach(entity);
}
_dbContext.Entry(entity).State = EntityState.Modified;
}
public IEnumerable<T> Execute<T>(string sprocname, object args)
{
var argProperties = args.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
//Get SQL Parameters Using Reflection
var parameters = argProperties.Select(propertyInfo => new System.Data.SqlClient.SqlParameter(
string.Format("@{0}", propertyInfo.Name),
propertyInfo.GetValue(args, new object[] { })))
.ToList();
//Build SQL Query to Execute Query using Parameters
string queryString = string.Format("{0}", sprocname);
parameters.ForEach(x => queryString = string.Format("{0} {1},", queryString, x.ParameterName));
string format = queryString.TrimEnd(',');
//Finally Execute Query
return _dbContext.Database.SqlQuery<T>(format, parameters.Cast<object>().ToArray());
}
public IEnumerable<T> Execute<T>(string sql)
{
return _dbContext.Database.SqlQuery<T>(sql);
}
public void Execute(string sql, object args)
{
var argProperties = args.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
//Get SQL Parameters Using Reflection
var parameters = argProperties.Select(propertyInfo => new System.Data.SqlClient.SqlParameter(
string.Format("@{0}", propertyInfo.Name),
propertyInfo.GetValue(args, new object[] { })))
.ToList();
//Finally Execute Query
_dbContext.Database.ExecuteSqlCommand(sql, parameters.Cast<object>().ToArray());
}
public void Execute(string sql)
{
_dbContext.Database.ExecuteSqlCommand(sql);
}
public Operation<int> SaveChanges()
{
var operation = new Operation<int>();
try
{
int rows =_dbContext.SaveChanges();
operation.Succeeded = true;
operation.Message = "Changes were Saved Successfully";
operation.Result = rows;
}
catch (DbEntityValidationException dbEx)
{
var message = "Entity Validation Failed: ";
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
message += $"\n{validationError.PropertyName}-{validationError.ErrorMessage}";
}
}
operation.Succeeded = false;
operation.Message = message;
}
catch (Exception ex)
{
while (ex.InnerException != null) ex = ex.InnerException;
operation.Message = ex.Message;
operation.Succeeded = false;
}
return operation;
}
public void Dispose()
{
if (_dbContext != null)
{
_dbContext.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment