Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Last active August 17, 2016 16:00
Show Gist options
  • Select an option

  • Save valerysntx/5d9ca947bc8aa7f71796f86b3eb76c99 to your computer and use it in GitHub Desktop.

Select an option

Save valerysntx/5d9ca947bc8aa7f71796f86b3eb76c99 to your computer and use it in GitHub Desktop.
Row-Level Access in Generic Repository
using Models;
using System;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
namespace Repository
{
public interface IGenericRepository<T>
{
IQueryable<T> CustomizeGet(Expression<Func<T, bool>> predicate);
void Add(T entity);
IQueryable<T> GetAll();
}
public class GenericRepository<TEntity, DbContext> : IGenericRepository<TEntity>
where TEntity : class, new() where DbContext : Models.Context, new() // fake context
{
private DbContext _entities = new DbContext();
public IQueryable<TEntity> CustomizeGet(Expression<Func<TEntity, bool>> predicate)
{
IQueryable<TEntity> query = _entities.Set<TEntity>().Where(predicate);
return query;
}
public void Add(TEntity entity)
{
int userId = Program.UserId; // fake UserId
if (typeof(IUser).IsAssignableFrom(typeof(TEntity)))
{
((IUser)entity).UserId = userId;
}
_entities.Set<TEntity>().Add(entity);
}
public IQueryable<TEntity> GetAll()
{
IQueryable<TEntity> result = _entities.Set<TEntity>();
int userId = Program.UserId; // fake UserId
if (typeof(IUser).IsAssignableFrom(typeof(TEntity)))
{
User me = _entities.Users.Single(c => c.Id == userId);
if (me.Type == UserType.Admin)
{
return result;
}
else if (me.Type == UserType.Ordinary)
{
string query = $"{nameof(IUser.UserId).ToString()}={userId}";
return result.Where(query);
}
}
return result;
}
public void Commit()
{
_entities.SaveChanges();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment