• No results found

119Creating the application’s DbContext

Querying the database

119Creating the application’s DbContext

2.2.2 Creating an instance of my application’s DbContext

In chapter one I showed you one way set up the application’s DbContext by overriding its OnConfiguring method. The downside is that the connection string is fixed. In this chapter I use another approach.I want to use a different database for development and unit testing, and the application’s DbContext constructor provides that.

Listing 2.3 shows me providing the options for the database at the time I create my application DbContext called EfCoreContext. This listing’s based on what I use in my unit testing, as it has the benefit of showing you the component parts. In chapter five, which is about using EF Core in an ASP.NET Core application, I cover a more powerful way to create the application’s DbContext using a feature called dependency injection.

const string connection =

"Data Source=(localdb)\\mssqllocaldb;"+ "Database=EfCoreInActionDb.Chapter02;"+

This is the "connection string". Its format’s dictated by the sort of database provider and hosting you’re using

"Integrated Security=True;"; var optionsBuilder =

I need a EF Core

DbContextOptionsBuilder<> instance to be able to set the options we need. new DbContextOptionsBuilder

<EfCoreContext>(); optionsBuilder.UseSqlServer(connection);

I’m accessing a SQL Server database and use the UseSqlServer method from the Microsoft.EntityFrameworkCore.S qlServer library, need the connection string. var options = optionsBuilder.Options;

using (var context = new EfCoreContext(options))

This creates the all-important EfCoreContext using the options we’ve set up. Note that I use a 'using' statement, as the DbContext is disposable, i.e. it should be 'disposed' once you’ve finished your data access {

var bookCount = context.Books.Count();

This code uses the DbContext to find out how many books are in the database. //... etc.

At the end of listing 2.3 I create an instance of the EfCoreContext inside a using state- ment. This is because DbContext has an IDisposable interface and should be disposed after you’ve used it. From now on, if you see a variable called context it was created using the code in listing 2.3, or a similar approach.

2.2.3 Creating a database for your own application

TIP If you’re running my example application downloaded from the Git repo that goes with this book, you don’t need to use the Migrate commands that follows. If run in development mode, it uses the command EnsureCre- ated to create the database. This is less flexible than the Migrate, but it doesn’t need you to type any commands.

A few ways to create a database using EF Core work, but the normal way’s to use EF Core’s Migrations feature. This uses your application’s DbContext and the entity classes, like the ones I’ve described, as the model for the database structure. The Add-

Migration command first models your database and then, using that model, builds commands to create a database that fits that model.

Besides creating the database, the great thing about Migrations is that it can update the database with any changes you make in the software. If you change your

entity classes or any of your application’s DbContext configuration, the Add-Migration command will build a set of commands to update the existing database.

To use the migration feature you need to install one extra EF Core NuGet libraries in your application called Microsoft.EntityFrameworkCore.Tools to your applica- tion startup project. This allows you to use the Migrate commands in the Visual Stu- dio Package Manager Console (PMC). The ones we need are:

1 Add-Migration MyMigrationName

This creates a set of commands that migrate the database from its current state to a state that matches your application’s DbContext and the entity classes when you run your command. The MyMigrationName shown in the command’s the name used for the migration.

2 Update-Database

This will apply the commands created by the Add-Migration command to your database. If there’s no database, it creates one. If there’s a database that migrate created last time, it will update it.

NOTE You can also use EF Core’s command line Interface (CLI) to run these commands—see https://docs.microsoft.com/en-us/ef/core/miscellaneous /cli/dotnet. In this book, I use Visual Studio 2017 based commands.

An alternative to using the Update-Database command’s to call the context.Data- base.Migrate() method in the startup code of your application. This is particularly useful for a ASP.NET Core web application that’s hosted—I cover this in chapter five, including some of its limitations.

NOTE Although EF Core’s Migrate feature’s useful, it doesn’t cover all types of database structure changes. Also, for some projects the database’s defined and managed outside of EF Core, which means you can’t use EF Core’s Migrate feature. I explore the various options available for database migra- tion, with their pros and cons, in chapter eleven.

WHATTODOIFYOURAPPLICATIONUSESMULTIPLEPROJECTS?

If your application has a separate project for the application’s DbContext from the main, startup application (the book-selling site example application does), then the Add-Migration command’s more complex.

In the example book-selling site my application’s DbContext is in a project called DataLayer, and my ASP.NET Core application’s in a project called EfCoreInAction (I describe why this is later in this chapter). To add an EF Core migration the Add- Migration commands would be:

121