Getting Started with EF Core on ASP.NET Core with a New database

In this tutorial, you build an ASP.NET Core MVC application that performs basic data access using Entity Framework Core. The tutorial uses migrations to create the database from the data model.

You can follow the tutorial by using Visual Studio 2017 on Windows, or by using the .NET Core CLI on Windows, macOS, or Linux.

View this article's sample on GitHub:

Prerequisites

Install the following software:

Create a new project

  • Open Visual Studio 2017
  • File > New > Project
  • From the left menu, select Installed > Visual C# > .NET Core.
  • Select ASP.NET Core Web Application.
  • Enter EFGetStarted.AspNetCore.NewDb for the name and click OK.
  • In the New ASP.NET Core Web Application dialog:
    • Make sure that .NET Core and ASP.NET Core 2.1 are selected in the drop-down lists
    • Select the Web Application (Model-View-Controller) project template
    • Make sure that Authentication is set to No Authentication
    • Click OK

Warning: If you use Individual User Accounts instead of None for Authentication then an Entity Framework Core model will be added to the project in Models\IdentityModel.cs. Using the techniques you learn in this tutorial, you can choose to add a second model, or extend this existing model to contain your entity classes.

Install Entity Framework Core

To install EF Core, you install the package for the EF Core database provider(s) you want to target. For a list of available providers, see Database Providers.

For this tutorial, you don't have to install a provider package because the tutorial uses SQL Server. The SQL Server provider package is included in the Microsoft.AspnetCore.App metapackage.

Create the model

Define a context class and entity classes that make up the model.

  • Right-click on the Models folder and select Add > Class.

  • Enter Model.cs as the name and click OK.

  • Replace the contents of the file with the following code:

    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    
    namespace EFGetStarted.AspNetCore.NewDb.Models
    {
        public class BloggingContext : DbContext
        {
            public BloggingContext(DbContextOptions<BloggingContext> options)
                : base(options)
            { }
    
            public DbSet<Blog> Blogs { get; set; }
            public DbSet<Post> Posts { get; set; }
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }
    
            public ICollection<Post> Posts { get; set; }
        }
    
        public class Post
        {
            public int PostId { get; set; }
            public string Title { get; set; }
            public string Content { get; set; }
    
            public int BlogId { get; set; }
            public Blog Blog { get; set; }
        }
    }
    

A production app would typically put each class in a separate file. For the sake of simplicity, this tutorial puts these classes in one file.

Register the context with dependency injection

Services (such as BloggingContext) are registered with dependency injection during application startup. Components that require these services (such as MVC controllers) are provided these services via constructor parameters or properties.

To make BloggingContext available to MVC controllers, register it as a service.

  • In Startup.cs add the following using statements:

    using EFGetStarted.AspNetCore.NewDb.Models;
    using Microsoft.EntityFrameworkCore;
    
  • Add the following highlighted code to the ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<BloggingContext>
            (options => options.UseSqlServer(connection));
        // BloggingContext requires
        // using EFGetStarted.AspNetCore.NewDb.Models;
        // UseSqlServer requires
        // using Microsoft.EntityFrameworkCore;
    }
    

A production app would typically put the connection string in a configuration file or environment variable. For the sake of simplicity, this tutorial defines it in code. See Connection Strings for more information.

Create the database

The following steps use migrations to create a database.

  • Tools > NuGet Package Manager > Package Manager Console

  • Run the following commands:

    Add-Migration InitialCreate
    Update-Database
    

    If you get an error stating The term 'add-migration' is not recognized as the name of a cmdlet, close and reopen Visual Studio.

    The Add-Migration command scaffolds a migration to create the initial set of tables for the model. The Update-Database command creates the database and applies the new migration to it.

Create a controller

Scaffold a controller and views for the Blog entity.

  • Right-click on the Controllers folder in Solution Explorer and select Add > Controller.
  • Select MVC Controller with views, using Entity Framework and click Add.
  • Set Model class to Blog and Data context class to BloggingContext.
  • Click Add.

The scaffolding engine creates the following files:

  • A controller (Controllers/BlogsController.cs)
  • Razor views for Create, Delete, Details, Edit, and Index pages (Views/Movies/*.cshtml)

Run the application

  • Debug > Start Without Debugging
  • Navigate to /Blogs

  • Use the Create New link to create some blog entries.

    Create page

  • Test the Details, Edit, and Delete links.

    Index page

Additional Resources