The whole point of having a repository pattern is to decouple the various layers in your application in addition to making it easier to unit test your application.
The proper way to implement the repository pattern is to have an interface that defines four basic methods...
public interface IEntity
{
string Id { get; set; }
}
public interface IRepository<T> where T : IEntity
{
void Add(T entity);
void Remove(T entity);
void Create(T entity);
T Find(string id);
}
Now you can implement this interface for any of your entities, let's imagine you're creating a blog, a blog would contain posts right?
So, create a PostsRepository...
public class Post : IEntity
{
public Post()
{
this.Id = Guid.NewGuid().ToString();
}
public string Id { get; set;}
}
public class PostsRepository : IRepository<Post>
{
public void Add(Post entity);
/// etc
}
That's how it's supposed to be implemented, though the above example does not take into consideration that the data access logic is composed using Entity Framework.
Now that we know what the Repository Pattern is, let's move on to integrating Entity Framework...
In the PostsRepository
class, you would have a property that could reference your Entity Framework DbContext. Remember that PostsRepository
is a concrete implementation which will be used for any other class that is dependent on IRepository.
So why bother, seems like a lot of trouble for little gain, but you'd be wrong...
Imagine that you're attempting to validate content within a post that is submitted to a website... How would isolate the validation logic whilst avoiding making any calls to the database?
You could either create hand rolled mock objects that implement IRepository that doesn't reference EntityFramework as the data source (this is a long winded approach)... or you could simply use frameworks available out there already such as Moq
, which you use to create a fake implementation of IRepository.
So, in short what you need to start studying is:
- Dependency Inversion
- Repository Pattern
- Decorator Pattern
- N-Tier architecture
- Onion architecture
All of those will have a major impact on how maintainable your application will be once the code base has grown. You don't need to be an expert, that will come through making mistakes and biting a few bullets here and there... but having a general understanding of those will make tremendous difference even in the short term.