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

Accessing the Database Directly from DbContext

DbContext communicates with the database any time you execute a query or call SaveChanges. You can take advantage of DbContext’s access to the database through its Database property. With DbContext.Database, you can communicate directly with the database if your application calls for such interaction.

You may not have realized that Code First leverages the Database property for the database initialization tasks. It uses the Database.Exists property to check for the database. Database has a Delete method and a Create method and even one called CreateIfNotExists. All four of these members are public, so you could use them directly if you want to. In fact, early technical previews of Code First required developers to use those properties and methods to perform database initialization manually. It wasn’t until later that the SetInitializer classes were introduced which encapsulated the most common initialization workflows.

Once your DbContext is instantiated, it will be aware of the connection string it will use to work with the database, even if you haven’t yet performed any tasks that would initiate the connection. You can use the DbContext.Database property to interact with the connection or the database itself.

Not all of the Database members require direct interaction with the database. For example, here is some code that writes the connection string of the Database associated with that context to a console window using the Database.Connection ...

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