Integrating ASP.NET Core 2 Web API and Entity Framework Core 2

ASP.NET Core 2 Web API and Entity Framework Core 2.0 (EF Core 2) are the two latest Microsoft’s offerings into Open Source world gaining momentum. We will learn to integrate them together, being cross platform technologies you are not bound to Windows for learning.

I am using Windows OS, SQL Server Express Edition and Visual Studio 2017 IDE to integrate, you can use the steps to integrate on Linux or OS X using Visual Studio Code, database like MySql, Postgresql as of now

What is Entity Framework Core 2 (EF Core 2)?

Entity Framework (EF) Core is a lightweight and extensible version of the popular Entity Framework data access technology.

EF Core is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write. EF Core supports many database engines. Here is the providers list

So lets started for using EF Core 2 in ASP.Net Core 2 Web API

Creating ASP.NET Core Web API

This is a continuation of Creating ASP.NET Core WebAPI, recommend to read it to move further here. You can still create your own project too.

Adding Entity Framework Core packages

Just like ASP.NET Core is completely modular, same way EF Core is also designed to be modular i.e. the packages are split into granular with more focused functionality instead of including everything.

It has EF Core packages for the various databases; as we are using SQL Server Express Edition, we will add its packages. Open *.csproj in Web API project to add EF Core package for SQL Server. You can add it using NuGet also.

Add appropriate packages for database by referring EF Core Database providers list

Create the Database Context

We are working on Contacts data model from the previous link, so let’s create database context for it

DbContext class coordinates Entity Framework functionality for a given data model is the database context class. Let’s create Contexts folder (name it as you like) and in it, C# class named ContactsContext, copy below code in it

Breaking down code

  1. Microsoft.EntityFrameworkCore namespace containing DbContext class to derived.
  2. ContactsContext class derives from the DbContext class to be coordinator for data model and database
  3. DbContextOptions allows us DI the configuration, provider details for DbContext to work. Lots of other functionality exists to be explored later
  4. When EF creates the database, the tables have to be created too, for these C# properties that have DbSet are created as tables. At present we have only one table, if you have many tables please create DbSet properties accordingly.

Providers & Database Connection string

The database context we created above is independent of the database used, in this example, we are using SQL Server so we need to use appropriate provider and its database connection string to perform the database related operation.

Add this code in ConfigureServices method of Startup.cs. Don’t forget to include namespace Microsoft.EntityFrameworkCore.

UseSqlServer configures the ContactsContext to connect to Microsoft SQL Server Database.

DefaultConnection is connection string for connecting to database, it should be added in appsettings.json

Tools for EF migration

At present to work with EF Core, we have command line options for operations like adding/ modifying migrations (generating database schema in C# classes), updating database.

Edit *.csproj or use NuGet manager to add Microsoft.EntityFrameworkCore.Tools package and include EF to the run from command line options. The highlighted code should be present included.

Running EF Core commands

We included EF Core packages, created DbContext, added a provider with connection string and added tools to work command line.

For this simple example, we have two steps to follow

Init Migrations

The data models, DbSet needs to be prepared for creating SQL scripts, add init migrations command will create C# class for model snapshot i.e. database snapshot. Run the following command from project folder shown in figure

  • dotnet – executes .NET Core commands
  • ef – Entity Framework Core commands, available only if we adding EF tooling in project.json
  • add init – Initiates EF migrations for context

After this run the following command to create the Contacts database in SQL Server

Open Sql Server Express to view the Contacts database created. It’s fairly simple.

web api

Contacts DB created using EF commands

Calling ContactsContext from repository

In the previous example I have used IContactsRepository, this gets called from Web API Controllers. IContactsRepository is singleton DI injected; here is where we call use EF (Dbcontext) to call database.

We are injecting ContactsContext using DI, this was setup in Startup.cs file, using _context we can work with DbSet’s

Running WEB API and Source Code

Using either POSTMAN or Fiddler or Swagger UI, we can do testing of it.

The ContactsAPI github repo contains source code. Many improvements need to be made, but its good enough to get started.

You may also like...

18 Responses

  1. sejong shon says:

    Any plan to implement role based authentication using Identity & JWT? I recommend this repo

  2. Mark ZHUKOVSKY says:

    Should change services.AddSingleton(); to use .AddTransient – agree?

  3. Mark ZHUKOVSKY says:

    InvalidOperationException: Cannot consume scoped service from singleton

  4. Guruprasad says:

    Hi , It is very good lession. I have downloaded the code and trying to run from chrome. But having the below Error.

    URL: http://localhost:5000/api/Contacts

    GET http://localhost:5000/api/Contacts 500 (Internal Server Error

    favicon.ico:1 GET http://localhost:5000/favicon.ico 404 (Not Found)



    • You need to have Sql Server express edition, run the migrations. Did you do those?

      • Guruprasad Y says:

        Hi Mithun,

        Thank you for the info.
        I have installed SQL server in local and also done migration command and its went fine.I can access Values controller from browser. But only i am not able to access Contacts controller methods.. API/Contacts

        Please suggest is there something i am missing.

        Thanks in advance.


        • First, do POST & then do GET request. Initial DB won’t have any data in the table.

          • Guruprasad Y says:

            actually, when I comments the below constructor from class ContactsRepository then I am able to get debug for Get and Post Request.
            But otherwise its giving 500 Error code. I am not sure what is the problem.

            public ContactsRepository(ContactsContext context)
            _context = context;

            Please suggest.

  5. Sudhir Thanki says:

    C:\Source\CoreApi\src\CoreApi>dotnet ef migrations add init
    Project CoreApi (.NETCoreApp,Version=v1.0) was previously compiled. Skipping com
    Unhandled Exception: System.MissingMethodException: Entry point not found in ass
    embly ‘Microsoft.EntityFrameworkCore.Design, Version=, Culture=neutral, P

    Following is my project.json file.

    “dependencies”: {
    “Microsoft.NETCore.App”: {
    “version”: “1.0.1”,
    “type”: “platform”
    “Microsoft.AspNetCore.Mvc”: “1.0.1”,
    “Microsoft.AspNetCore.Routing”: “1.0.1”,
    “Microsoft.AspNetCore.Server.IISIntegration”: “1.0.0”,
    “Microsoft.AspNetCore.Server.Kestrel”: “1.0.1”,
    “Microsoft.Extensions.Configuration.EnvironmentVariables”: “1.1.0-preview1-final”,
    “Microsoft.Extensions.Configuration.FileExtensions”: “1.1.0-preview1-final”,
    “Microsoft.Extensions.Configuration.Json”: “1.1.0-preview1-final”,
    “Microsoft.Extensions.Logging”: “1.1.1”,
    “Microsoft.Extensions.Logging.Console”: “1.1.0-preview1-final”,
    “Microsoft.Extensions.Logging.Debug”: “1.1.0-preview1-final”,
    “Microsoft.Extensions.Options.ConfigurationExtensions”: “1.0.0”,
    “Microsoft.EntityFrameworkCore.InMemory”: “1.1.1”,
    “Microsoft.EntityFrameworkCore.SqlServer”: “1.0.1”,
    “Microsoft.AspNetCore.Identity.EntityFrameworkCore”: “1.0.0”,
    “Microsoft.EntityFrameworkCore.Tools”: “1.0.0”

    “tools”: {
    “Microsoft.AspNetCore.Server.IISIntegration.Tools”: “1.0.0-preview2-final”,
    “Microsoft.EntityFrameworkCore.Tools”: {
    “version”: “1.0.0-preview2-final”,
    “imports”: [

    “frameworks”: {
    “netcoreapp1.0”: {
    “imports”: [

    “buildOptions”: {
    “emitEntryPoint”: true,
    “preserveCompilationContext”: true

    “runtimeOptions”: {
    “configProperties”: {
    “System.GC.Server”: true

    “publishOptions”: {
    “include”: [

    “scripts”: {
    “postpublish”: [ “dotnet publish-iis –publish-folder %publish:OutputPath% –framework %publish:FullTargetFramework%” ]

    I am getting above error during migration. Any thought on this?

  6. Rick Dowdall says:

    Hello Mithun – In your blog you state in the Init Migrations section: Run the following init command from the project folder, I am assuming that this command runs in the VS 2015 project using the VS Command Prompt. I want to confirm before I proceed. Is this correct?


  7. Zafer Balkan says:

    With your first tutorial I could implement my first Web API through creating the sample than modifying it. Now I’m trying to learn the concept of Web API and db. I have some questions.

    1. On web API, where is the data from HTTP post messages kept? Where is the JSON data saved? On the repository? Does that works like some kind of NoSQL?
    2. By using EF, how do we manage the data flow? Do we insert the data into tables via HTTP POST messages and query them via HTTP GET?
    3. About the answer of the question above, can we implement our own model for optimization? For example, a ContactsApi is a write-less, read-more kind of system. So can we just insert new contact to the database but GET a contact from repository for performance concerns? This might be a silly example but I’d like to understand the concept.
    4. We use phone numbers as id’s. Can’t we use random numbers we create for identity?

    Thanks for the tutorial. I’m looking forward to reading the new post about using Microsoft.Extensions.Logging.

    • Thanks Zafer for your comments, glad to hear it helped you in getting started. Your questions are interesting.
      Point 3 – General recommendation (best practice) for Web API is we should perform operations according to HTTP verbs like GET should retrieve data, POST should perform Insert etc. Mixing them like do POST and same method does GET leads to violation of RESTful principles. There is not much performance benefit if you mix them.

      Point 1 – Using Model binding the POST messages are serialized to class (Contacts in our example), this model class with data can be used into database using EF or any other data technologies

      Point 2 – First insert data using POST, ASP.NET Core Web API gives link generator which gives back GET url for retrieve data. That’s another article in itself.

      Point 4 – We can use anything as identity, but my example is such that.

      Let me know if you have more queries.

      • Zafer Balkan says:

        Thanks. As a best practice, I’ve been thaugh that “whatever table you use in a db, just create a unique id even if it’s not needed” just because of the possibility of the requirements’ change. Now I’m working on that. That’s why I’ve asked that thing. Thank you again.

  1. October 12, 2016

    […] Integrating EF Core with ASP.NET Core Web […]

  2. December 7, 2016

    […] on December 6, 2016 submitted by /u/mithunvp [link] [comments] Leave a […]

  3. August 23, 2017

    […] We will be continuing with the ContactsAPI build with Entity Framework 2.0. […]

  4. November 11, 2017

    … [Trackback]

    […] Read More: […]

Leave a Reply