Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Repository Pattern have repetition of code so what will be benefit?

I am understanding repository pattern in c#. I am confused when i study about generic repository pattern. There is lot of repetition in it. i have some question about this pattern.

I am using Entity Framework code first approach and i have two model classes

Student
Teachers

How many generic interface i will use for example if i have one generic interface

public interface IRepository<TEntity>
{
   IQueryable<TEntity> FindAll(Expression<Func<TEntity, bool>> where = null);

   TEntity FindOne(Expression<Func<TEntity, bool>> where = null);       
}

So this interface can be use in both model classes. if Student class have more methods where i can define these methods? for example

public class StudentRepo<TEntity> : IRepository<TEntity> where TEntity : class
{
    public virtual IQueryable<TEntity> FindAll(Expression<Func<TEntity, bool>> where = null)
    {
        return null != where ? Context.Set<TEntity>().Where(where) : Context.Set<TEntity>();
    }

    public virtual TEntity FindOne(Expression<Func<TEntity, bool>> where = null)
    {
        return FindAll(where).FirstOrDefault();
    }

    public void update()
    {
    }

    public int FindId()
    {
    }
}

So i have added two new methods update() and FindId() in StudentRepo where can I define these methods?

If I want to add these two methods in IRepository then I have to call these methods for Teacher class. what will be benefit of it? Is this better approach if i create separate interface for both classes? like IStudent and ITeacher so i can define those methods which i want to use and unnecessary methods will not be in use.

Kindly guide me i am so confused.

like image 703
Shoaib Ijaz Avatar asked Dec 09 '22 15:12

Shoaib Ijaz


1 Answers

You can have one implementation for the IRepository that you have, something like:

public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
    public virtual IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> where = null)
    {
        // implementation ...
    }

    public virtual TEntity FindOne(Expression<Func<TEntity, bool>> where = null)
    {
        // implementation
    }

    public void Update(TEntity entity)
    {
        // update your entity ...
    }

    // etc...
}

Then have your own repository inheriting from it:

public class StudentRepository : GenericRepository<Student>
{
    // here you get all the goodies + you can add your own stuff
}

And:

public class TeacherRepository : GenericRepository<Teacher>
{
    // here you get the same goodies, you don't need to re-implement them
}

This way you don't have to re-implement all the methods defined in the generic repository, you can however add your own more complex methods.

like image 137
Dimitar Dimitrov Avatar answered Dec 11 '22 09:12

Dimitar Dimitrov