DEV Community

Renuka Patil
Renuka Patil

Posted on

Entity Framework in .net core 6.0 - Code first and Database first approach

Using Entity framework we achieve database connectivity.

ORM (Object Relational Mapping)

  • To address data access requirements of ASP.NET CORE MVC application, you can use ORM framework.

  • ORM is tool for storing data from domain objects(model) to relational database.

  • Simplifies the process of accessing data from application.

  • ORM is tool for storing data from domain objects(MODEL CLASSES) to relational database(SQL SERVER DB).

  • To achieve data access requirements - access and storing data in the database.

entity framework

  • Entity Framework Core is the new version of Entity version of Entity Framework after EF6 but it is redesigned. Its open-source, lightweight, extensible and cross-platform version of EF.

  • It is an enhancement ADO.NET that gives developers an automated mechanism for accessing and storing the data in database.

  • EF Core is intended to be used with .NET Core applications. However, it can also be used with standard .NET 4.5+ framework based applications.

Entity framework

Drawback of ADO.net - we need to write much code to connect to database

In EF core, we need to create only classes in the project, ORM will create tables in the database also if there are already database it creates properties according to that too.

EF core supports two development approaches
1) Code First approach
2) Database First approach


1) Code First approach

first we write database classes and it is automatically generated tables in the database.

Code first

  • The EF Core creates database objects based on model classes that you create to represent application data.

  • Allows you to define your own model by creating custom classes Then you can create database based on the model.

code first flow

*Step 1: Install 3 packages *

1. microsoft.EntityFrameworkCore.SqlServer 

2. microsoft.EntityFrameworkCore.Tools - Manage migrations and to scafffold(automatic generation of code) a DbContext.

3. microsoft.EntityFrameworkCore.Design - Contains all design-time logic for EF core.
Enter fullscreen mode Exit fullscreen mode

Step 2: Model class - Student class

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WeApp1.Models
{
    public class Student
    {
        [Key]
        public int Id { get; set; }

        [Column("StudentName", TypeName ="Varchar(100)")]
        public string Name { get; set; }

        [Column("StudentGender", TypeName = "Varchar(100)")]
        public string Gender { get; set; }

        public int Age { get; set; }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Db Context class → StudentDBContext

using Microsoft.EntityFrameworkCore;

namespace WeApp1.Models
{
    public class StudentDBContext : DbContext
    {
        public StudentDBContext(DbContextOptions options) : base(options)    
                                      // base used to call parent class 
        {
        }

        public DbSet<Student> Students { get; set; }  //Table in Database
     }
}

Enter fullscreen mode Exit fullscreen mode
  • This DbContext class interacts with database.
  • Manages database connection and it is used to retrieve and save data in database
  • An instance of this class represents a session with Database which can be used to query and save instance of your entities to a Database.
  • DbContext is the combination of unit of work and repositories.
  • DbContext can be used to defined the database context class after creating a model class.

  • DbSet type to define one or more properties, where T → type of an object that needs to be stored in the database.

  • DbContextOptions → for dbcontext class do useful work, it needs an instance of DbContextOptions class which carries configuration info like connection string, database provider etc,.

Step 4: Add connection string in → appsettings.json file

"ConnectionStrings": {
"dbcs":"server=server_name;Database=database_name;Trusted_Connection=True;" 
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Registering string in program.cs file

using Microsoft.EntityFrameworkCore;
using WeApp1.Models;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();

var provider = builder.Services.BuildServiceProvider();

var config = provider.GetRequiredService<IConfiguration>();

builder.Services.AddDbContext<StudentDBContext>(item => item.UseSqlServer(config.GetConnectionString("dbcs")));

var app = builder.Build();
Enter fullscreen mode Exit fullscreen mode

Step 6: Add migrations and run the migrations
Open package manager console and run the commands to create tables in SQL database

Package manager console

PM> add-migration codefirstCreateDb

PM> update-database
Enter fullscreen mode Exit fullscreen mode

After running these 2 commands you will see the database created and student table name is there

Image description

Step 7: Controller

using Microsoft.AspNetCore.Mvc;
using WeApp1.Models;

namespace WeApp1.Controllers
{
    public class HomeController : Controller
    {
        private readonly StudentDBContext studentDb;

        public HomeController(StudentDBContext studentDb)
        {
            this.studentDb = studentDb;
        }
        public ViewResult Index()
        {
            var stdData = studentDb.Students.ToList();
            return View(stdData);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 8: Create view using scafffolding

Scaffolding

Using Scaffold add all actions at once

Index view

This is solution explorer will look

Image description

After you build and run the project this is how output will look

Image description

2) Database First approach

  • In the Database First approach the EF core creates model classes and properties corresponding to the existing database objects, such as tables and columns.
  • The Database First approach is applicable in scenerio where a database already exists for the application.

Database first

using Scaff

Database first flow

Step 1: install packages

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Design
Enter fullscreen mode Exit fullscreen mode

Step 2: Execute command for scaffholding

  • Automatically generates model class and dbcontext file
Scaffold-DbContext "server=servername; database=databasename; trusted_connection=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Enter fullscreen mode Exit fullscreen mode
  • If we update our database then how we can update our model and DbContext class? Run this command in package manager console
Scaffold-DbContext "server=servername; database=databasename; trusted_connection=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models-force
Enter fullscreen mode Exit fullscreen mode

You will see models class will be automatically created

Image description

Step 3: Move connection string to appsettings.json file
In TestCodeFirstDbContext class, you will see the connection string there, you should move that to appsettings.json file for security purpose.

Step 4: Registering connection string in Program.cs file

var provider = builder.Service.BuildServiceProvider();

var config = provider.GetRequiredService<IConfiguration>();

builder.services.AddDbContext<CodeFirstDbContext>(item ⇒ item.UseSqlServer(config.GetConnectionString("dbcs")))

Enter fullscreen mode Exit fullscreen mode

** Step 5: Controller**

private readonly CodeFirstDbContext  CodeFirstDb;

    public HomeController(CodeFirstDbContext  CodeFirstDb)

    {

         this.CodeFirstDb = CodeFirstDb;

    }

      public IActionResult Index()

     {

        var data = CodeFirstDb.Students.ToList();

        return View(data);

     }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Add view for this as we did in code first approach

Image description

The output you will see
Image description

Hope you learn from this post, Happy Learning!

Top comments (1)

Collapse
 
yashkotti profile image
yash-kotti

Like this detailed blog
Keep it up