Entity Framework Core 3: Interface on DBContext good practice?

1.2k views Asked by At

Is creating an Interface on DBContext good practice in Entity Framework Core 3.1? Does Microsoft have any documentation on this?

We know that Mocking DBContext in Unit testing is bad practice, however how about creating an Interface over it?

https://learn.microsoft.com/en-us/ef/core/testing/

"However, we never try to mock DbContext or IQueryable. Doing so is difficult, cumbersome, and fragile. Don't do it."

Resources: Why DbContext doesn't implement IDbContext interface?

1

There are 1 answers

7
Steve Py On BEST ANSWER

If your objective is to facilitate unit testing code that interacts with the DbContext then I would recommend looking at implementing the Repository pattern alongside a Unit of Work to manage the DbContext lifetime scope and commits. I have outlined effective ways to implement flexible, and easily test-able repository classes in various answers, but this one probably sums it up best: (How to set multiple services from Entity Framework Core on Repository Pattern?)

I recommend avoiding generic repository implementations and embracing the power of EF's IQueryable support to build an extremely simple layer to mock that can provide efficient and flexible querying.

The last detail is if you do want to support async querying through the repository and want to unit test those, an invaluable tip to support this can be found here: (Unit-testing .ToListAsync() using an in-memory)