Question

Has anyone read this article on www.asp.net titled "Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10)"

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

In the article it says: "This generic repository will handle typical CRUD requirements. When a particular entity type has special requirements, such as more complex filtering or ordering, you can create a derived class that has additional methods for that type."

Can anyone explain in detail how can I create a derived class and use these additional methods? Do I put additional methods in the generic repository as virtual methods?

Please help, I cannot figure out how to do this. Thanks a lot.

Was it helpful?

Solution

Here is an example:

public class GenericRepository<TEntity> where TEntity : class
{
    public virtual TEntity GetByID(object id)
    {
        // ...
    }

    public virtual void Insert(TEntity entity)
    {
        // ...
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        // ...
    }
}

These methods would apply to all your entities. However let's say you want to get a User by an email (a property that only the user has) you can extend the GenericRepository with your additional method:

public class UserRepository : GenericRepository<User>
{
    // Now the User repository has all the methods of the Generic Repository
    // with addition to something a bit more specific
    public User GetByEmail(string email)
    {
        // ..
    }
}

Edit - In the article they're using a GenericRepository in the Unit of Work, but when your repository is more specific you use it instead. For example:

public class UnitOfWork : IDisposable
{
    private GenericRepository<Department> departmentRepository;
    private GenericRepository<Course> courseRepository;

    // here is the one we created, which is essentially a GenericRepository as well
    private UserRepository userRepository;

    public UserRepository UserRepository
    {
        get
        {

            if (this.userRepository== null)
            {
                this.userRepository= new UserRepository(context);
            }
            return this.userRepository;
        }
    }

   // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top