Step by step: .NET Core and Entity Framework Core

by Carlos Mendible on 11 Jul 2016 » dotNet, dotNetCore

Today I’ll show you how to create a small console application with a Step by step: .NET Core and Entity Framework Core example.

First be aware of the following prerequisites:

**OS** **Prerequisites**
Windows Windows: You must have .NET Core SDK for Windows or both Visual Studio 2015 Update 3* and .NET Core 1.0 for Visual Studio installed.
linux, mac or docker checkout .NET Core

Now let’s start:

1. Create a folder for your new project


Open a command promt an run

mkdir efcore

2. Create the project


cd efcore
dotnet new

3. Create a settings file


Create an appsettings.json file to hold your connection string information. We’ll be using **SQLite **for this example, so add these lines:

{
  "ConnectionStrings": {
    "Sample": "Data Source=sample.db"
  }
}

4. Modify the project file


Modify the project.json to add the EntityFrameworkCore dependencies and also specify that the appsettings.json file must be copied to the output (**buildOptions **section) so it becomes available to the application once you build it.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true,
    "copyToOutput": {
      "include": "appsettings.json"
    }
  },
  "dependencies": {
    "Microsoft.Extensions.Configuration": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.EntityFrameworkCore": "1.0.0",
    "Microsoft.EntityFrameworkCore.Sqlite": "1.0.0"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

5. Restore packages


You just modified the project.json file with new dependencies so please restore the packages with the following command:

dotnet restore

6. Create the Entity Framework context


Create a SampleContext.cs file and copy the following code

namespace ConsoleApplication
{
    using Microsoft.EntityFrameworkCore;

    /// <summary>
    /// The entity framework context with a Students DbSet 
    /// </summary>
    public class StudentsContext : DbContext
    {
        public StudentsContext(DbContextOptions<StudentsContext> options)
            : base(options)
        { }

        public DbSet<Student> Students { get; set; }
    }

    /// <summary>
    /// A factory to create an instance of the StudentsContext 
    /// </summary>
    public static class StudentsContextFactory
    {
        public static StudentsContext Create(string connectionString)
        {
            var optionsBuilder = new DbContextOptionsBuilder<StudentsContext>();
            optionsBuilder.UseSqlite(connectionString);

            // Ensure that the SQLite database and sechema is created!
            var context = new StudentsContext(optionsBuilder.Options);
            context.Database.EnsureCreated();

            return context;
        }
    }

    /// <summary>
    /// A simple class representing a Student
    /// </summary>
    public class Student
    {
        public Student()
        {
        }

        public int Id { get; set; }

        public string Name { get; set; }

        public string LastName { get; set; }
    }
}

7. Modify Program.cs


Replace the contents of the Program.cs file with the following code

namespace ConsoleApplication
{
    using System;
    using Microsoft.Extensions.Configuration;

    public class Program
    {
        public static void Main(string[] args)
        {
            // Enable to app to read json setting files
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            var configuration = builder.Build();

            // Get the connection string
            string connectionString = configuration.GetConnectionString("Sample");

            // Create a Student instance
            var user = new Student() { Name = "Carlos", LastName = "Mendible" };

            // Add and Save the student in the database
            using (var context = StudentsContextFactory.Create(connectionString))
            {
                context.Add(user);
                context.SaveChanges();
            }

            Console.WriteLine($"Student was saved in the database with id: {user.Id}");
        }
    }
}

8. Build


Build the application with the following command

dotnet build

9. Run


You are good to go so run the application

dotnet run

You can get the code here: https://github.com/cmendible/dotnetcore.samples/tree/master/efcore.sqlite.console

Hope it helps!