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. You use migrations to create the database from your EF Core model.

View this article's sample on GitHub.


Install the following software:

Create a new project in Visual Studio 2017

  • 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:
    • Ensure the options .NET Core and ASP.NET Core 2.1 are selected in the drop down lists
    • Select the Web Application (Model-View-Controller) project template
    • Ensure 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 your 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 List<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; }

In a real app you would typically put each class from your model in a separate file. For the sake of simplicity, this tutorial puts all the classes in one file.

Register your context with dependency injection

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

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

  • Open Startup.cs

  • Add the following using statements:

    using EFGetStarted.AspNetCore.NewDb.Models;
    using Microsoft.EntityFrameworkCore;

Call the AddDbContext method to register the context as a service.

  • Add the following highlighted code to the ConfigureServices method:

    // This method gets called by the runtime. Use this method to add services to the container.
    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;
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

Note: A real app would generally 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

Once you have a model, you can use migrations to create a database.

  • Tools > NuGet Package Manager > Package Manager Console
  • Run Add-Migration InitialCreate to scaffold a migration to create the initial set of tables for your model. If you receive an error stating The term 'add-migration' is not recognized as the name of a cmdlet, close and reopen Visual Studio.
  • Run Update-Database to apply the new migration to the database. This command creates the database before applying migrations.

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.

Run the application

Press F5 to run and test the app.

  • Navigate to /Blogs
  • Use the create link to create some blog entries. Test the details and delete links.



Additional Resources