Step by step: .NET Core and Entity Framework Core

Step by step: .NET Core and Entity Framework Core

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**
WindowsWindows: 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 dockercheckout .NET Core

Now let’s start:

Create a folder for your new project


Open a command promt an run

mkdir efcore

Create the project


cd efcore
dotnet new

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"
  }
}

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"
    }
  }
}

Restore packages


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

dotnet restore

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; }
    }
}

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}");
        }
    }
}

Build


Build the application with the following command

dotnet build

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/main/efcore.sqlite.console

Hope it helps!

Last modified December 12, 2024: new post (bf52b37)