Skip to content

Instantly share code, notes, and snippets.

@explorer14
Last active December 14, 2018 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save explorer14/1dd924471d3af65caf7d05c1560208af to your computer and use it in GitHub Desktop.
Save explorer14/1dd924471d3af65caf7d05c1560208af to your computer and use it in GitHub Desktop.
// type restricted to operate only on IDomainObject reference types
public class GenericRepository : IRepository where T : class, IDomainObject
{
private DbContext context;
public GenericSqlRepository(DbContext context)
{
this.context = context;
}
public async Task AddAsync(T domainObject)
{
this.context.Set<T>().Add(domainObject);
await this.context.SaveChangesAsync();
}
public async Task<IEnumerable<T>> GetListAsync(
Expression<Func<T, bool>> predicate)
{
IQueryable query = this.GetPredicatedIQueryable(predicate);
return await query.ToListAsync();
}
public async Task GetOneAsync(Guid id)
{
var entities = await this.GetListAsync(x => x.Id == id);
return entities.FirstOrDefault();
}
public async Task UpdateAsync(T updatedEntity)
{
this.context.Update(updatedEntity);
await this.context.SaveChangesAsync();
}
private IQueryable GetPredicatedIQueryable(
Expression<Func<T, bool>> predicate)
{
return this.context.Set().Where(predicate);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment