Gnanavel Sekar
Gnanavel Sekar

Reputation: 45

i would like to do the generic search option in repository pattern

Here i implemented generic repository pattern for do the CRUD operation at the same time , i would like to do the search option as well, anyone can you tell me query to do generic search options, my code is below

public interface IRepository<T> where T : class
{
    IEnumerable<T> GetAll();
    T GetById(object Id);
    T Insert(T obj);
    void Delete(object Id);
    T Update(T obj);
    void Save();
    long Count();
}
public class Repository<T> : IRepository<T> where T : class
{
    private PegasusPlusEntities context;
    private DbSet<T> dbSet;
    public Repository()
    {
        context = new PegasusPlusEntities();
        dbSet = context.Set<T>();
    }
    public IEnumerable<T> GetAll()
    {
        return dbSet.ToList();
    }
    public T GetById(object id)
    {
        return dbSet.Find(id);
    }
    public T Insert(T obj)
    {
        dbSet.Add(obj);
        Save();
        return obj;
    }
    public void Delete(object id)
    {
        T entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }
    public void Delete(T entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }
    public T Update(T obj)
    {
        dbSet.Attach(obj);
        context.Entry(obj).State = EntityState.Modified;
        Save();
        return obj;
    }
    public long Count()
    {
        return dbSet.Count();
    }

    public void Save()
    {
        try
        {
            context.SaveChanges();

        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {


                }
            }
        }
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (context != null)
            {
                context.Dispose();
                context = null;
            }
        }
    }
}

thanks in advance...

Upvotes: 4

Views: 3423

Answers (1)

Nkosi
Nkosi

Reputation: 247451

There are a few ways to do this but here is a simple example

Add a method to the current interface to allow for generic search

IEnumerable<T> Search(Expression<Func<T,bool>> predicate);

A simple implementation can look like this

public IEnumerable<T> Search(Expression<Func<T,bool>> predicate) {
    return dbSet.Where(predicate).ToList();
}

An example of it in use would be

var repository = new Repository<Person>();
var searchResults = repository.Search(p => p.FirstName == "John" && p.LastName == "Doe");

Upvotes: 9

Related Questions