there are several way to implement repository pattern.
usually it depends on the reason you need this pattern.
for example if you need this pattern to create a common way to access different kinds of databases (sql, mysql, mongo) then you need to create a "searching" that can works in both of them.
if you need a simple wrapper over entity framework
that's the one i use :
public interface IRepository<TEntity>
where TEntity : class
{
int BulkInsert(System.Linq.IOrderedEnumerable<TEntity> items);
int Delete(TEntity item);
int DeleteRange(System.Collections.Generic.IEnumerable<TEntity> items);
System.Collections.Generic.IEnumerable<TEntity> Get();
TEntity Get(params object[] keys);
System.Collections.Generic.IEnumerable<TEntity> Get(Func<tentity,bool> lambda);
int Insert(TEntity item);
int Update(TEntity item);
void Dispose();
}
public abstract class BaseRepository<TContext,TEntity> : IDisposable, IRepository<TEntity>
where TEntity : class
where TContext : DbContext, new()
{
public TContext Context { get; private set; }
private DbSet<TEntity> DbSet { get { return Context.Set<TEntity>(); } }
public BaseRepository()
{
Context = new TContext();
}
public TEntity Get(params object[] keys)
{
Context.Configuration.AutoDetectChangesEnabled = false;
var e = DbSet.Find(keys);
Context.Configuration.AutoDetectChangesEnabled = true;
return e;
}
public IEnumerable<TEntity> Get()
{
Context.Configuration.AutoDetectChangesEnabled = false;
var e = DbSet.ToList();
Context.Configuration.AutoDetectChangesEnabled = true;
return e;
}
public IEnumerable<TEntity> Get(Func<tentity,> lambda)
{
Context.Configuration.AutoDetectChangesEnabled = false;
var e = DbSet.Where(lambda).ToList();
Context.Configuration.AutoDetectChangesEnabled = true;
return e;
}
}
public class TestRepository<TEntity> : BaseRepository<dbtest,>
where TEntity : class
{
public TestRepository()
: base()
{
}
}
var users = new TestRepository< User>().Get(u => u.PhoneNumber.StartsWith("00") && u.IsDeleted == 0);
note my full version implements idisposable so you can put your new TestRepository< User>() inside a using statement