Repository Pattern – How to Implement for Complex Object Models

asp.net-mvcdesign-patternsentity-framework

Our data model has almost 200 classes that can be separated out into about a dozen functional areas. It would have been nice to use domains, but the separation isn't that clean and we can't change it.

We're redesigning our DAL to use Entity Framework and most of the recommendations that I've seen suggest using a Repository pattern. However, none of the samples really deal with complex object models. Some implementations that I've found suggest the use of a repository-per-entity. This seems ridiculous and un-maintainable for large, complex models.

Is it really necessary to create a UnitOfWork for each operation, and a Repository for each entity? I could end up with thousands of classes. I know this is unreasonable, but I've found very little guidance implementing Repository, Unit Of Work, and Entity Framework over complex models and realistic business applications.

Best Answer

First, you will run through every entity that you have and ask yourself :

Does it make sense to persist this entity alone?

What I mean here, is that in your object model, some entities are likely contained in others in a master-detail relationship. If your entity is highly dependant on another, do not create a repository for this entity alone because it won't likely be persisted by itself. Instead, you will create a repository for each parent class, and you will make sure that the child entities and other relations are persisted at the same time.

I don't like how they implemented the UnitOfWork pattern in the link you provided. I suggest you to do something more along these lines. You don't have to define one class per repository. The same class can be used for every repository, each having their own instance of the UnitOfWork class for the lifetime of the operation. You can also reuse the same UnitOfWork in different repositories for changes that you want persisted at the same time.