Home

Published

- 2 min read

Choose your poison: EF Core or Repository Pattern?

img of Choose your poison: EF Core or Repository Pattern?
Reach 6,200+ engaged devs by sponsoring this newsletter

4 months ago, a newsletter reader asked me this:

“I face a problem in abstracting the data layer from the business layer when I use Entity Framework Core. I can’t find the best practice for doing it properly. Do you have any advice?”

Great question.

The common answer you find online?
Use a Repository pattern.
This pattern abstracts the data access layer by providing common CRUD (Create, Read, Update, Delete) operations.

What are the arguments for using it?

  1. It provides an abstraction between database queries and business logic.
  2. It enables unit testing.

With the Repository pattern, you can change your database provider any time you want. And write unit tests as many as you want.
Sounds like a no-brainer, right?
Add a Repository, and it will solve all your problems.
After all, any problem in programming can be solved by adding another layer of abstraction…

..Except for the problem of having too many abstractions.

What do I mean?
Well, EF Core already does everything the Repository can do.

One. It provides an abstraction between database queries and business logic.

You can use LINQ methods to write the queries that EF Core translates to the raw SQL. It also supports different databases out of the box (MSSQL, PostgreSQL, MySQL, SQLite, Oracle, Cosmos, MongoDB…).
Besides, when was the last time you had to change the underlying database?

Two. You can write unit tests. EF Core has providers that don’t talk to external databases.

And keep all data in memory.
Yes, they don’t behave the same as the real EF Core providers. And can produce different results. But that’s why you should have integration tests that use the actual database.
Also, if you think you need abstract EF Core to write “proper” unit tests, a word of warning. Over-abstraction and over-mocking lead to over-fragile and over-complex tests.
I’ve seen those a lot in the 12 years of my career.

Therefore, when developers use Repository on top of the EF Core, they add abstraction over abstraction.
They do it because of the fear of the spaghetti code.
But instead, they end up with a lasagna code.
A layer upon a layer.
Upon a layer.
Where you need to change:

  • 3 interfaces,
  • 17 files
  • across 5 different projects

To return additional property from your API endpoint.

Therefore, the mindset I have about EF Core is:

Don’t think about EF Core as a database layer. Think about it as a Repository pattern that Microsoft built freely instead of you.

Hope this answers the question.

Related Posts

There are no related posts yet. 😢