© Eric Vogel 2021
E. VogelBeginning Entity Framework Core 5https://doi.org/10.1007/978-1-4842-6882-7_5

5. Creating a Database from Code

Eric Vogel1  
(1)
Okemos, MI, USA
 

So far we have created our entities and their metadata to instruct Entity Framework Core 5 what to create. As you will soon see, the process of taking those instructions and having them be interpreted by Entity Framework Core 5 to create your database is as simple as creating an initial migration and running that migration using Visual Studio. We will primarily be using the Microsoft SQL Server provider for Entity Framework Core in this book and thus will be creating a SQL Server database.

Setting the Connection String

The first step in creating a database from code in Entity Framework Core 5 is to define the connection string for your application. Open the appsettings.json file in your ASP.NET Core web app. Next, we add the connection string that will be used by our app by defining the “ConnectionStrings” property. For our app, we will be calling the name of the connection string “connection”, and it will point to a SQL database named “EfCore5WebApp” as seen in Listing 5-1.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "connection": "Server=(localdb)\mssqllocaldb;Database=EfCore5WebApp;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}
Listing 5-1

Adding a Connection String to appsettings.json

The example in Listing 5-1 is connecting to a local SQL Server database. You can see that from the connection string which includes the text “(localdb)”. Now that the connection string is set, we need to tell our web app to use that connection string. Open up the Startup.cs class file. In the ConfigureServices method, we use the AddDbContext() method to connect to our SQL Server as seen in the following code example:
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("connection")));
}
We are using the “UseSqlServer” extension method that was included in the Entity Framework Core 5 SQL NuGet package. Your Startup.cs class file should now look like Listing 5-2.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFCOre5WebApp.DAL;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace EFCore5WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("connection")));
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
Listing 5-2

Startup Class That Points to the SQL Server Database

Now that our application is pointed to the database, we can actually create the database through adding a migration.

Creating the Initial Migration

The next step in creating a database through code in Entity Framework Core 5 is to create an initial migration.

To create the initial migration, we can use the NuGet Package Manager Console and run the “Add-Migration” command passing in the name of our migration as the second parameter.

Let us now create the initial migration and name it “InitialCreate”. Open the NuGet Package Manager Console and change the Default project dropdown to your DAL project and run this command: “Add-Migration InitialCreate”. Also make sure your web project is set as the Startup project in your solution.

See Figure 5-1 as a reference.
../images/499766_1_En_5_Chapter/499766_1_En_5_Fig1_HTML.jpg
Figure 5-1

Creating Initial Migration

You will now see a Migrations folder added to your DAL project with a class file created for the actual migration as seen in Figure 5-2.
../images/499766_1_En_5_Chapter/499766_1_En_5_Fig2_HTML.jpg
Figure 5-2

Migrations Folder and Class File Created

You will now see a class file named InitialCreate that was created by the “Add-Migration” command. This file will look like Listing 5-3.
using Microsoft.EntityFrameworkCore.Migrations;
namespace EFCore5WebApp.DAL.Migrations
{
    public partial class InitialCreate : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "LookUps",
                columns: table => new
                {
                    Code = table.Column<string>(type: "nvarchar(450)", nullable: false),
                    Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    LookUpType = table.Column<int>(type: "int", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_LookUps", x => x.Code);
                });
            migrationBuilder.CreateTable(
                name: "Persons",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    FirstName = table.Column<string>(type: "nvarchar(255)", maxLength: 255, nullable: false),
                    LastName = table.Column<string>(type: "nvarchar(255)", maxLength: 255, nullable: false),
                    EmailAddress = table.Column<string>(type: "nvarchar(max)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Persons", x => x.Id);
                });
            migrationBuilder.CreateTable(
                name: "Addresses",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    AddressLine1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    AddressLine2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    City = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    State = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Country = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    ZipCode = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    PersonId = table.Column<int>(type: "int", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Addresses", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Addresses_Persons_PersonId",
                        column: x => x.PersonId,
                        principalTable: "Persons",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });
            migrationBuilder.CreateIndex(
                name: "IX_Addresses_PersonId",
                table: "Addresses",
                column: "PersonId");
        }
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Addresses");
            migrationBuilder.DropTable(
                name: "LookUps");
            migrationBuilder.DropTable(
                name: "Persons");
        }
    }
}
Listing 5-3

InitialCreate Migration Class

I will go over how to decipher this file and delve deeper into migrations in Chapter 14. Now that the migration is created, let’s run it to create our “EfCore5WebApp” database in the SQL Server instance defined in our appSettings.config file in our web project.

Creating the Database from the Migration

Lastly, we will create the database from the “InitialCreate” migration that we just created. Open the NuGet Package Manager Console and run the “Update-Database” command as seen in Figure 5-3.
../images/499766_1_En_5_Chapter/499766_1_En_5_Fig3_HTML.jpg
Figure 5-3

Running Our Migration

The “Update-Database” command is what we will use to update the database whenever we add a new migration to our project.

Connect to the New Database from Visual Studio

We are using LocalDb as our database, so we need to follow the steps in this section to connect to the database via Visual Studio. First, verify that the database was created. Open up a Command Prompt and run “SqlLocalDB.exe start” to start the LocalDb instance as seen in Figure 5-4.
../images/499766_1_En_5_Chapter/499766_1_En_5_Fig4_HTML.jpg
Figure 5-4

Starting a LocalDb SQL Server Instance

Next, we add a connection to our LocalDb instance through Visual Studio. Go to Tools ➤ Connect to Database. If you are using SQL Server or SQL Server Express, use that connection instead. To connect to our LocalDb, add a new SQL Server connection as seen in Figure 5-5.
../images/499766_1_En_5_Chapter/499766_1_En_5_Fig5_HTML.jpg
Figure 5-5

Adding a Database Connection

Then click the “OK” button. You should now be able to browse and query your newly created database as seen in Figure 5-6.
../images/499766_1_En_5_Chapter/499766_1_En_5_Fig6_HTML.jpg
Figure 5-6

Browsing Our Database

Summary

In this chapter, we have gone through the journey of creating a database using Entity Framework Core 5. First, we created the connection string that tells our app how to connect to a SQL Server database. Then we used Entity Framework tooling to create a migration by using the “Add-Migration” command that generated all the code to create our database schema. After that, we used Entity Framework tooling through the “Update-Database” command to run the migration code. Lastly, we started and connected to our created database. In the next chapter, we will see how to seed our newly created database with data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.46.221