Getting Start with Entity Framework Core 3.1 – Part I

Introduction:

What is EF core?

     EF core is a Microsoft’s Object Relational Mapper. It is a cross platform where you can build the application using EF Core and deploy it on windows, macOS, Linux and even on docker containers whether it is on premise or cloud. The main significant  on using the ORM is to increase the developer productivity and coding consistency.

Tooling:

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

Setting up the solution:

Step 1: Create an empty solution using Visual Studio, in my case I named it as EFCoreDemos, as shown in below figure.

Figure 1: Create a empty solution

Step 2: Create a new .NET Standard class library project for the Domain classes, in my case I named it as EFCoreDemo.Domain, as shown in the below figure

Figure 2: Create a Domain class library project

Let’s create a simple public class called User with following properties.

  • Id
  • Name

User.cs

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

Step 3: Create another .NET Standard class library project for the Data Model, in my case I name it as EFCoreDemo.Data, as shown in below figure.

Figure 3: Create a Data class Library project

 

Step 4: Install EF Core using NuGet Package Manager

Open NuGet Package Manager from the project EFCoreDemo.Data, search for Microsoft.EntityFrameworkCore.SqlServer and install it, because we going to use Sql Server for the data persistence as our data provider, it will download with all its dependencies.

Figure 4: Install EF Core using NuGet Package Manager

Let’s create a data model to drive the persistence of the domain class into the SQL server database. Create a new class and name it is AppDBContext because it is going to use EFCore DBContext class.

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

    }
}

This class need to be public and it’s need to be inherited from DbContext class , it provides all the logic of the EF core used for database interaction task. The DB Sets  which becomes as a wrappers while you interacting with context. The tables in the database will match with the Dbsets name.

Register the provider for the dbcontext by overriding OnConfiguring method   

The above OnConfiguring method is triggered when the EFCore instantiate the AppDbContext at runtime.

In my case I didn’t created EFCoreDemoDB database in my server, the EF core is capable of creating the database by reading the model by which the DB context describes it based on the classes it’s pointing to. It can be created on run-time or during the design time.

Step 5: Create a console application project for testing, to interact with the SQL Server using the context by writing and reading the data.

Figure 5: Create Console Application
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);
            }
        }
    }
}

From the above code the AddUser method is used to add the user and GetUsers method is used to get all users from the users table in the database.

Figure 6: Console output

The new user is added to the database .

Figure 7: Users table created in the EFCoreDemoDB

Summary:

  From this blog you have learned,

  1. What EF Core is for
  2. Created a data model with EF Core
  3. Learned about EF Core API’s packages

Reference:

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

Source Code – https://github.com/gowthamece/EFCore

Happy Coding !!!

gowthamk91

One thought on “Getting Start with Entity Framework Core 3.1 – Part I

Leave a Reply

%d bloggers like this: