Question

I'm developing a Course, Department, Student MVC application as part of learning MVC.

I've gone with a multi-tier design, i.e. Web, BLL, DAL.

My DAL has DbContext and a number of repositories. E.g. Student, Department, Course, Search, Audit...

Next looking into how I could share DbContext among the DAL repositories led me to read up alot on design patterns, and I ended up at Generic Repository, and Unit of Work (and a quick look at Dependency Injection).

I soon discovered the benefits of the Generic Repositoy and UoW. This would work great with Student, Department, Course... entities that fit CRUD functionality. I haven't coded this yet.

But when it came to fitting Search and Audit with Generic Repository and UoW, it wouldn't fit. Background: Why share DbContext between Search and Audit? I'd like to audit each search within the same transaction.

So I was stuck! Primarily because search functionality is read-only with no commits. And secondly both the Search and the Audit entities are very different - different from each other, and not CRUD-like. So a generic repository would not work well here for these two entities, as far as I can see.

Is there a way to share DbContext between two very different entities, e.g. Search and Audit?

The best approach I can come up with is to put audit functionality within the Search DAL repository. I don't like mixing these two entities, sounds somewhat ugly, but I guess I can make the exception given it is audit functionality.

Was it helpful?

Solution

The disadvantage of a Generic Repository is that not all entities support CRUD operations. A repository doesn't have to be CRUD. You can create entity specific repositories like the following.

public class Search
{
    public Search(DbContext dbContext);
}

public class AuditRepository
{
    public AuditRepository(DbContext dbContext);
}

A lot of developers do not like the generic(CRUD) repository for the following reason:

"not every entity can be deleted, not every entity can be added, not every entity has a repository" Source

Example is a repository that only has GetById. The requirements forbids create/update/delete.

public class UserRepository
{
    public User GetById(int id);
    {
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top