O'Reilly logo

Programming Entity Framework: DbContext by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reducing Database Hits in Testing with IDbSet

If you want to test a method such as GetTravelersOnFutureTrip without hitting the database, you’ll need to use abstractions of the context and sets that do not involve database interaction. What we’ll show you is the key parts of a more abstracted solution so that we can focus on the IDbSet interface.

As an alternative to the BreakAwayContext class, we’ll create another context that can create entities on the fly without depending on the database. But in order for us to use this alternative context with the repository, it will need to let us execute the code in the GetTravelersOnFutureTrip method. That means it will need, for example, the ability to create and execute queries. IDbSet gives us the capabilities that we need.

Not only does the DbSet class we’ve been using implement IDbSet, it also inherits from DbQuery. And it’s the DbQuery class that adds in the reliance on the database. In our alternative context, we’ll use properties that implement IDbSet but are not derived from DbQuery. That means we’ll need a concrete implementation of IDbSet, giving us the ability to perform set logic and queries without interacting with a database, effectively “faking” the database interaction. So let’s start by creating this concrete class.

Creating an IDbSet Implementation

Because IDbSet implements IQueryable and IEnumerable, this new class will need to implement members of all three interfaces. Example 8-9 shows the entire listing of the FakeDbSet ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required