Integrate Entity Framework Core in .NET Core Application

Kundan Zalte
.Net Programming
Published in
2 min readMar 2, 2020

In this tutorial you will learn how to create and use .Net Core Console application with Entity Framework Core step by step.

Prerequisites

Create a new project

1.Start visual studio 2019
2.Select Create a new project
3.Select Console App (.Net Core) and Click Next.
4.You will see a pop-up like below , give project name and click Create.

Creating Console App

Install Entity Framework Core

  1. Tools -> NuGet Package Manager -> NuGet Package Manager -> Package Manager Console
  2. Type below command for installation of Entity Framework Core for particular Database Provider(SQL Server in our case).
  • PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer

Tip : For installation of EF Core you need to execute “Microsoft.EntityFrameworkCore” and then for Particular Database Provider you need to execute “Microsoft.EntityFrameworkCore. provider_package_name” , instead you can execute “Microsoft.EntityFrameworkCore. provider_package_name” directly.

Creating the Model

Entity Framework Core needs a Model to communicate with the underlying database.

We need to create a context class and entity classes in-order to create model.

  • Right-click on the project and select Add > Class
  • Enter ModelName.cs as the name and click Add
  • Add below code in that file
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace EFcoreDemo
{
public class SchoolContext : DbContext
{
public DbSet<Student> Students{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=. \SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");
}
}
public class Student
{
public int RollNo{ get; set; }
public string Name{ get; set; }
public string Address{ get; set; }
}
}

Create the database using Migration

For Database creation execute below commands in Project Manager console

  • Install-Package Microsoft.EntityFrameworkCore.Tools
  • Add-Migration InitialCreate
  • Update-Database

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.

Insert Operation

Now we will do some basic Insertion operation

using (var context = new SchoolContext()) {

var std = new Student()
{
Name = "Joe"
};

context.Students.Add(std);
context.SaveChanges();
}

--

--

Kundan Zalte
.Net Programming

Software Engineer @MasterCard | Angular , React , .Net, Oracle, Cybersecurity