(C# Language) EF Core - Creating a Database

Database connectivity is required in almost every project. It is best done with the help of EF Core libraries. The good thing is that the steps for database connectivity are fairly standardized now. The same steps are used for C# console applications, the same are for a C# winforms, C# WPF and even C# web applications. This tutorial walks you through the steps required for creating a database. In the next tutorials we shall explain the create, read, update and delete operations.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Step 1 - Add Nuget Packages

Create a C# console project for the latest version of .NET Core.

Database connectivity is done through EF Core. For this we need to add two nuget packages. Use the Tools menu to open package manager console. Type Install-Package Microsoft.EntityFrameworkCore.Sqlite on the command prompt. This command obtains all the necessary libraries for connectivity to a sqlite database. There are other database providers also - microsoft sql server, mysql and so on. Every provider has published their nuget packages - so you will have to take a look at their specific documentation.


PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite

Hit Enter and allow the process to complete. If everything goes well then you should see a success message.

Again type the Install-Package Microsoft.EntityFrameworkCore.Tools on the package manager console.


PM> Install-Package Microsoft.EntityFrameworkCore.Tools

This command adds additional libraries for EntityFramework in general. Allow it to complete to success.

Video Explanation (see it happen!)

Please watch the following youtube video:

Step 2 - Add Model Classes

A model class maps to a table in a database. We suggest adding a models folder to your project and keep all model classes in that folder.

Open the solution explorer and add a folder called Models. Next add a class called Blog to this folder.

Double click the file to examine the source code.


// model class that maps to a table 

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


public record class Blog
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ID { get; set; }

  public String? Heading { get; set; }
}

We have added a record class Blog. It contains two properties - ID and Heading. The ID has been marked as primary key by using [Key] attribute. We have also marked the property as auto generated, auto incrementing by using the attribute [DatabaseGenerated].

The Blog table will contain two columns ID and Heading.

Step 3 - Add ProjectContext

A project context maps to a database. Add a file called ProjectContext to the models folder. Double click and open this file. We have added a class called ProjectContext that inherits from DbContext.


// DbContext that maps to the database 

internal class ProjectContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; } = default!;

    private readonly string _dbPath;

    public ProjectContext(string dbName)
    {
        _dbPath = Path.Combine(Environment.CurrentDirectory, dbName);
    }

    protected override void OnConfiguring(
                            DbContextOptionsBuilder options)
    {
        options.UseSqlite($"Data Source={_dbPath}");
    }
}


Add a property called DbSet<Blog> Blogs. This property is a collection of Blog items. We can view it as a table in the database.

Next add a constructor to set the path to the database file. The path is contained in string _dbPath.

The OnConfiguring method should be over-ridden to set the database options. We have used it to specify that we shall use UseSqlite as our database.

Step 4 - Add Migrations

Now we have to create the physical database. The recommended method is to use migrations feature of ef core.

Migrations are used to keep the physical database in sync with the C# projectcontext and model classes.

Open the package manager console again and add a migration by using the Add-Migration Initial_Create command.


// add migration of any readable name 
// to create a database 

PM>Add-Migration Initial_Create

We have given a readable name to the migration called Initial_Create. We could have given any name, but experts suggest that we should give readable names.

Hit Enter and allow the command to finish.

Now open the solution explorer again. If everything is done correctly, then we should see a folder called Migrations. This folder contains auto-generated classes for migration.

Step 5 - Program.cs File

Finally, let us complete the Program.cs file.


// program.cs file 

using var db = new ProjectContext();

if (db.Database.GetPendingMigrations().Any())
{
  db.Database.Migrate();

  Console.WriteLine("All migrations applied!");
}

First of all create an instance of ProjectContext.

Our next step is to apply the migrations.

Next we check if there are any pending migrations. The function GetPendingMigrations gives a collection of migrations that have not been yet applied to the database. Whenever a migration is applied, an entry is made in a special table in the same database. EFCore uses this table to compare the migrations that exist in C# code but do not exist in the tables of the database.

If there are pending migrations, then we use the Database.Migrate() function to apply them.

Run the Project

Now run the project. We verify that the console opens and all migrations are applied.

We can examine the debug directory that it contains the database file.

We are now ready to create, read, update and delete records from the database. Thanks!


This Blog Post/Article "(C# Language) EF Core - Creating a Database" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.