Getting Started With Entity Framework Core - Console

This walkthrough demonstrates the minimum required to create a database using Entity Framework Core in a .Net Core Console application. The walkthrough assumes that you have .Net Core SDK installed and that you have a suitable development environment/text editor. Visual Studio Code will be used in this example.

Creating a .Net Core Console application

If you have a version of Visual Studio that supports .Net Core (2017 or greater), you can use the project templates to create a new .Net Core console application. Alternatively, you can use a command line tool to create and build the project. You can use the Terminal that's integrated into Visual Studio Code for this.

Create a folder named EFCoreDemo and then open it in Visual Studio Code.

Press Ctrl + ' to open a new Terminal window and then type the following commands:

> dotnet new console        
> dotnet add package Microsoft.EntityFrameworkCore.SqlServer
> dotnet add package --version 1.1.0-msbuild3-final Microsoft.EntityFrameworkCore.Tools 
> dotnet restore      
> dotnet run          

The commands above

  • scaffolds a blank .NET Core console appliction
  • adds the Entity FrameworkCore and EF Core tooling packages from Nuget to the project
  • restores all packages
  • builds and runs the console application

This results in a minimal console application:

.NET Core Console Application

Modify the generated .csproj file to include the following section:

<ItemGroup>
    <DotNetCliToolReference
        Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
        Version="1.0.0-msbuild3-final" />
</ItemGroup>

This step is only necessary if the .csproj file wasn't automatically modified to add the entry when the Tools package was installed. See https://github.com/aspnet/EntityFramework/issues/7358.

Once you have made this amendment, you can test to see if ef commands are available to you by typing the following command in the terminal window:

dotnet ef -h

This should result in the initial help for the EF tools being displayed:

EF commands Help

Creating A Model

Add a new file named EFCoreDemoContext.cs and add the following code to it:

using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo
{
    public class EFCoreDemoContext : DbContext
    {
        public DbSet<Book> Books { get; set; }
        public DbSet<Author> Authors { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=.\;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true");
        }
    }
}

Note: The model, particularly the DbContext class, is declared inside a namespace. If you don't place your context class in a namespace, you may come up against this long running open bug when adding your migration.

Next, add a new file named Author.cs and add the following code to it:

using System.Collections.Generic;

namespace EFCoreDemo
{ 
    public class Author
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public ICollection<Book> Books { get; set; } = new List<Book>();
    }
}

Finally, add a new file named Book.cs and add the following code to it:

namespace EFCoreDemo
{ 
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }
}

This code defines classes for two entities - Book and Author that participate in a fully defined one-to-many relationship. The code also includes a class named EFCoreDemoContext that inherits from DbContext. This class has two DbSet properties that represent the tables in the database (which is yet to be created). The EFCoreDemoContext class also includes a method named OnConfiguring where the connection string for a SQL Server database is defined. You should change this to suit your environment and database provider.

Adding A Migration

Migrations are used to keep the database schema in sync with the model. There is no database at the moment, so the first migration will create it and add tables for the entities represented by the DbSet properties on the EFCoreDemoContext that you added.

Enter the following command in the Terminal window:

dotnet ef  migrations add CreateDatabase

A new folder named Migrations is added to the project. It contains the code for the migration and a model snapshot.

Migrations Folder

Enter the following command to execute the migration:

dotnet ef database update

The database is created but all of the string fields are unlimited in size (nvarchar(MAX) in SQL Server).

Database created

Modifying The Database With Migrations

In the next section, you will modify the model to set limits to the size of selected string properties, and then use migrations to push those changes to the database schema.

Add the following to the using directives at the top of Author.cs and Book.cs:

using System.ComponentModel.DataAnnotations;

Modify the Book and Author entities so that they look like this:

public class Book
{
    public int BookId { get; set; }
    [StringLength(255)]
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}
public class Author
{
    public int AuthorId { get; set; }
    [StringLength(50)]
    public string FirstName { get; set; }
    [StringLength(75)]
    public string LastName { get; set; }
    public ICollection<Book> Books { get; set; } = new List<Book>();
}

In the Terminal, type the following command:

dotnet ef migrations add LimitStrings

followed by

dotnet ef database update

This will scaffold a migration that will alter the size of the Book's Title field and the Author's FirstName and LastName fields. You should also get a warning that the scaffolded migration could lead to data loss. In this case, there is no data to be lost so the warning can be ignored.

Once the migration has been applied, the database schema will be altered. Here's how the modified Author table should look:

Author Table

Working With Data

Open the Program.cs file and replace the existing content with the following:

using System.Collections.Generic;

namespace EFCoreDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new EFCoreDemoContext())
            {
                var author = new Author {
                    FirstName = "William",
                    LastName = "Shakespeare",
                    Books = new List<Book>
                    {
                        new Book { Title = "Hamlet"},
                        new Book { Title = "Othello" },
                        new Book { Title = "MacBeth" }
                    }
                };
                context.Add(author);
                context.SaveChanges();
            }
        }
    }
}

Execute the following command from the command line:

dotnet run

This will cause the code in the console application's Main method to execute, and the author and all books will be added to the database. You can verify this by querying the Books table using your preferred database management tool:

Books table

You can also verify it by changing the content of Program.cs as follows:

using static System.Console;

namespace EfCoreDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new EFCoreDemoContext())
            {
                foreach(var book in context.Books)
                {
                    WriteLine(book.Title);
                }
            }
        }
    }
}

Then execute the following command form the Terminal:

dotnet run

All going well, this should result in the titles of all three books being printed to the console window:

Read Data


Created:
Last updated: 05/03/2017 19:52:33
Proficiency Level: Beginner