Christian Gollhardt Christian Gollhardt - 2 years ago 376
SQL Question

Stored Procedures in Entity Framework without Repository Pattern

I am a little bit confused between the repository pattern and the Entity Framework.

In this answer, I have learned, it is bad to create a repository on top of Entity Framework for these reasons:

  • EF implements

  • EF implements a generic repository

  • The
    pattern is for abstract the database away from the business logic, which Entity Framework does

Instead of creating a repository on top of EF, we should use a service.

Now the problem:

What is, if I decide for performance reason to replace some Linq query with a stored procedure call, like mentioned here? This answer suggest to use some kind of repository pattern.

It feels dirty, if I would call a stored procedure directly in the service layer, since the database would no longer be abstracted from the business logic.

How would I abstract the stored procedure call? Or is it ok, to call it from the Service layer?

Answer Source

The reason why it's bad to have a repo on top of EF is that, in many cases, developers also expose IQueryable which defeats the purpose of the pattern. You can certainly have a repository (which is a service, btw) that uses EF as an internal implementation detail.

The relation between Repository and EF is that the Repository might use EF, but the client (using the repo) shouldn't be aware of that. EF is NOT a repository and while it can be used as one, it's yet another case of developers missing the point.

It's ok to use EF directly in CRUD apps, without pretending you're using the Repository pattern, those apps don't really need it.

In your case, the repository implementation should allow you to change it however you see fit, because the interface shouldn't be affected; that's why a repository interface only works with business objects as defined by the business model.

In a properly architecture, you wouldn't do linq or invoke SProcs directly, because those are persistence layer details. The rest of the app doesn't know about them. You can have repositories, query services etc working (as interfaces) with the concepts (business objects, view models, read models) that are known by the calling layer and only those services' implementation know about EF or SPRocs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download