Richard Banks
Richard Banks

Reputation: 2983

Entity Framework 4.1 generic repository

Using Entity Framework 4.1 and am trying to create a repository layer above as a test. Basically I'm playing around with it to become familiar as I'm new to Entity Framework and the repository pattern. I've followed some tutorials and have created a generic repository. The repository is initiated like so:

CentralDataRepositoryEntities CentralDataRepositoryEntities = new CentralDataRepositoryEntities();

Repository<Group> Rep = new Repository<Group>(CentralDataRepositoryEntities);
IEnumerable<Group> Groups = Rep.Get<Group>(g => g.JorMGroupId == 114);

Console.WriteLine(Group.Single());

Repository<Job> Rep1 = new Repository<Job>(CentralDataRepositoryEntities);
IEnumerable<Job> Jobs = Rep1.Get<Job>(j => j.jobId == 2138);

Console.WriteLine(Job.Single());

I'd prefer it if I didn't have to initiate a new repository every time. Is there a way I can create the repository and then use generic methods instead? E.g.:

Repository Rep = new Repository(CentralDataRepositoryEntities);
IEnumerable<Group> Groups = Rep.Get<Group>(g => g.JorMGroupId == 114);
IEnumerable<Job> Jobs = Rep.Get<Job>(j => j.jobId == 2138);

Is this a good idea? Why would you create a separate repository for each type and what's the performance hit on creating multiple repositories?

Upvotes: 4

Views: 799

Answers (2)

ebb
ebb

Reputation: 9397

Just to clarify: Are you trying to make a "universal" repository that can be used by multiple ORM's, or is it only for EF? If the latter it's a waste of time as such a pattern is already implemented. DbContext is what you would call "Unit Of Work", and the Set method it expose, is to create a Repository for the specificed type.

An example:

using(var ctx = new MyContext()) // Unit of Work
{
    var userRepository = ctx.Set<User>(); // Creates user repository
    var logRepository = ctx.Set<Log>(); // Creates log repository
    userRepository.Add(newUser); // Adds a "pending" item to the userRepository
    logRepositor.Add(logMsg); // Adds a "pending" item to the logRepository

    ctx.SaveChanges(); // Adds the "pending" items all at once.
}

by pending I mean the changes aren't saved to the database yet.

Upvotes: 1

Eranga
Eranga

Reputation: 32447

Having such a repository will violate Single responsibility principle. Single repository should only be responsible for managing single type of entity.

This generic repository pattern will only work for simple scenarios. There will be case where you will need additional method in the repository for specific entities.

Upvotes: 1

Related Questions