How to Configure Entity Framework Core 3.1 In .NET Core – PART I

In this post we will discuss what is Entity Framework Core and How does it work. We will also discuss that how to configure entity framework core in your .NET Core applications.

What is EF core and How does it work?

As the name suggests, EF core is a Microsoft product that maps objects and relationships. In other words, EF Core is a cross-platform development tool that can be used to build your application, deploy it on Windows, macOS, Linux, and even on docker containers whether the installation is on-premise or in the cloud. Developers can be more productive and code consistency is improved by using the ORM.

The tools:

  •  2019 Visual Studio
  •  SQL Server
  • .NET Core 3.1 SDK

Here are the steps for setting up the solution:

Here is how I created an empty solution using Visual Studio, EFCoreDemos in my case.

Configure Entity Framework Core

To create the Domain classes, create an EFCoreDemo.Domain project in .NET Standard, in my case I named it EFCoreDemo.Domain. 

Configure Entity Framework Core

The following properties should be present in a user class that we will create.

  • Id
  • Name

User.cs

namespace EFCoreDemo.Domain
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

EFCordDemo.Data is my name for the Data Model project in .NET Standard, as shown in the figure below.

Configure Entity Framework Core

With NuGet Package Manager, install EF Core

Microsoft.EntityFrameworkCore.SqlServer can be installed from the project EFCoreDemo.Data using NuGet Package Manager, since SQL Server is our data provider.

Configure Entity Framework Core

In order to maintain the domain class in SQL server, we need to create a data model. Because it will be using EFCore DBContext, create a new class called AppDBContext.

AppDBContext.cs

using EFCoreDemo.Domain;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.Data
{
    public class AppDBContext: DbContext
    {
            public DbSet<User> Users { get; set; } // The user class is from Domain project
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=[Provide user SQL server Name]; Initial Catalog = EFCoreDemoDB; Integrated Security=SSPI"); 
        }

    }
}

EF core logic for database interaction is provided by this class, which is public and inherited from DbContext. While interacting with context, DB Sets act as wrappers. There will be a match between the name of the database tables and the name of the DbSet.

Override the OnConfiguring method to register a provider for the database context   

At runtime, the AppDbContext is instantiated by EFCore and the OnConfiguring method is called.

Since I did not create the EFCoreDemoDB database in my server, the EF core can create it based on the model that is described by the DB context by reading the classes it refers to. You can create it at runtime or during design.

As part of the testing, create a console application project on the SQL Server that can interact with the data by writing and reading it.

Configure Entity Framework Core
using EFCoreDemo.Data;
using EFCoreDemo.Domain;
using System;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        private static readonly AppDBContext context = new AppDBContext(); 
        static void Main(string[] args)
        {
            context.Database.EnsureCreated();// Don't use this statement in production code
            Console.WriteLine("---------Before Add----------");
            GetUsers();
            AddUser();            
            Console.WriteLine("----------After Add-----------");
            GetUsers();
            Console.WriteLine();
            Console.ReadKey();
        }
        public static void AddUser()
        {
            var user = new User { Name = "Gowtham" };
            context.Users.Add(user); // Add user record in database 
            context.SaveChanges();// Saves all changes made in this context to the database
        }
        public static void GetUsers()
        {
            var users = context.Users.ToList();
            Console.WriteLine($"User count is {users.Count}");
            foreach(var user in users)
            {
                Console.WriteLine(user.Name);
            }
        }
    }
}

This code adds a user and gets all users from the database’s users table using AddUser and GetUsers methods.

Configure Entity Framework Core

An entry is made in the database for the new user.

Configure Entity Framework Core

Brief summary:

  You have learned the following from this blog:

  1. What EF Core and How does it work?
  2. Used EF Core to create a data model
  3. Discovered the packages that make up the EF Core API

Reference:

https://docs.microsoft.com/en-us/ef/core/

Leave a Comment