Connecting to SQL Server from Entity Framework Core Using C#

Connecting to SQL Server from Entity Framework Core Using C#

First we will create a .net core console project and then use entity framework core to perform database operation. Steps to create .net core console application

  1. Start Visual Studio 2019
  2. Click on File -> New -> New Project -> Visual C# -> .NET Core -> Console App (.NET Core)
  3. Give some useful name to application and then click on Ok. I have created EntityFrameworkCoreExample1

code1.png

Key Elements to learn from this article is

  1. Create database tables and insert some values
  2. How to create database connection string
  3. Creating database context for entity framework
  4. Creating business entity for performing database operations
  5. Calling entity in main function

Create Database Tables

Open your database and create tables of your choice . For example I have created Employee table in my database named Dummy which will be used in EntityFrameworkCoreExample1 application.

pic2.png

Create Database Connection String

Now we can create database connection class which can be used in multiple places.

namespace EntityFrameworkCoreExample1
{
    public class DatabaseConnection
    {
        public static string ConnectionString
        {
            get
            {
                return ($"Server=localhost;Database=Dummy;Trusted_Connection=True;MultipleActiveResultSets=true;");
            }
        }
    }
}

Note – we can also read connection string from appsetting.json file in .net core console application . for accessing these configuration , we need to install below library using nugget package console.

code2.png

Create Database Context

If you have already worked on previous Entity Framework , then you must be aware about DbContext and their functionalities.
Here , all your database context file must be inherited from DbContext Microsoft.EntityFrameworkCore.DbContext class.

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreExample1
{
    public class EntityFrameworkContext :DbContext
    {
        public EntityFrameworkContext():base()
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            if(!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(DatabaseConnection.ConnectionString);
            }
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }
}

Notice , we have used UseSqlServer extension method of DbContextOptionBuilder. optionsBuilder.UseSqlServer(DatabaseConnection.ConnectionString)

Create Business Entity Class

Now we can create business entity class which will handle database operations with the help of EntityFrameworkContext class. Ideally , object structure of business entity class should match the database object , but it’s not necessary. Business entity class can have different number of fields and name in business class . The type must be matched with the database tables fields.

Now let’s look at simple example of fetching data from database tables , so here is Employee class that will be dealing with Employee tables.

namespace EntityFrameworkCoreExample1
{
    public class Employee
    {
        public Employee()
        {

        }

        public int EmpId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

After creating business entity class , we have to register that business class (Employee) in EntityFrameworkContext class a. Create a DbSet Property for handling Database object - public DbSet<Employee> Employee { get; set; } b. Add Entity class Employee in OnModelCreating Method modelBuilder.Entity<Employee>().HasKey(t => t.EmpId);

Now EntityFrameworkContext class will be look like

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreExample1
{
    public class EntityFrameworkContext :DbContext
    {
        public EntityFrameworkContext():base()
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            if(!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(DatabaseConnection.ConnectionString);
            }
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().HasKey(t => t.EmpId);
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Employee> Employee { get; set; }


    }
}

In above code, HasKey property .HasKey(t => t.EmpId) is the primary key of database tables.

Create Data Transfer Object Class (DTO)

Now everything is ready and we can fetch or add or update the database objects. But directly accessing Context class directly is not advisable. So we can create a DTO class which will be handling all the database operations using EntityFrameworkContext class.

Let’s think of a situation where we have to fetch all the Employee records or update few Employee records, so instead of changing at multiple places, we can update in DTO (one place) and then able to perform the actions. So it will reduce the code as well as improve the testablitiy of the function.

So , let’s create DTO class which will be handling the database operations on Employee class. We will be creating a simple method Named GetAllEmployee which will be fetching all the employees from the database.

using System;
using System.Collections.Generic;
using System.Linq;

namespace EntityFrameworkCoreExample1
{
    public class EmployeeDTO : IDisposable
    {
        public List<Employee> GetAllEmployee()
        {
            List<Employee> allEmployees = new List<Employee>();
            using(var context=new EntityFrameworkContext())
            {
                allEmployees = context.Employee.ToList<Employee>();
            }
            return allEmployees;
        }
        public void Dispose()
        {
           // throw new NotImplementedException();
        }
    }
}

Calling method in main

Now let’s call the DTO class object in main method and check whether it is working or not. Below is the code which will read all Employee data and read all field of Employee table.

using System;
using System.Collections.Generic;

namespace EntityFrameworkCoreExample1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> allEmployee = null;
            using(var eDto=new EmployeeDTO())
            {
                allEmployee = eDto.GetAllEmployee();
            }
            foreach(var emp in allEmployee)
            {
                Console.WriteLine("EmpID, FirstName, LastName, Age, Email, Address, Department");
                Console.WriteLine(emp.EmpId + "," + emp.FirstName + "," + emp.LastName + "," + emp.Age + "," + emp.Email + "," + emp.Address + "," + emp.Department);

            }
            Console.ReadLine();
        }
    }
}

Note :- I have not handled the Exception in this code, I will write another blog for handling exceptions.

If you like the blog, please share it so that it will be reached to many and may be useful for someone.

You can also follow me on twitter - twitter.com/CodeAsItIs1 or Instagram - instagram.com/CodeAsItIs

I have also a youtube channel where i can upload programming video at - youtube.com/c/codeasitis Please have a look , share , subscribe it.

Thank you,

Dhiraj Kumar