ASP.NET Core Application With Code-First Entity Framework Core

Entity Framework Core: 

Why Entity Framework Core?

  • Entity Framework (EF) Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology.
  • EF Core can serve as an object-relational mapper (O/RM), enabling .NET developers to work with a database using .NET objects.
  • 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. 
  • OS Platform support: Windows, Linux, Mac.

Entity Framework Core uses a provider model to access many different databases. It includes providers as NuGet packages which you need to install. Database Providers and the Nuget packages are:            

              SQL Server       Microsoft.EntityFrameworkCore.SqlServer
              MySQL              MySql.Data.EntityFrameworkCore
              PostgreSQL       Npgsql.EntityFrameworkCore.PostgreSQL
              SQLite                Microsoft.EntityFrameworkCore.SQLite
              SQL Compact    EntityFrameworkCore.SqlServerCompact40
              In-memory         Microsoft.EntityFrameworkCore.InMemory


EF Core supports two development approaches:
  • Code-First 
  • Database-First

EF Core mainly targets the code-first approach and provides little support for the database-first approach because the visual designer or wizard for the DB model is not supported as of EF Core 2.0.

In the code-first approach, EF Core creates the database and tables using migration based on the conventions and configuration provided in your domain classes. This approach is useful in Domain-Driven Design (DDD).

In the database-first approach, EF Core creates the domain and context classes based on your existing database using EF Core commands. This has limited support in EF Core as it does not support visual designer or wizard.

Code-First Approach in ASP.NET Core:

Follow the step by step procedure for implementing Code-First in ASP.NET Core Application.

Step:1
Create a Database in SQL Server. Here I created the "DB_Profile" database. Here we only create a database we will not add tables. For adding tables we will use code-first in  ASP.NET Core Web Application. 

Step:2
Create ASP.NET Core Application Project. 
Open visual studio 2019 and select Create a new project.
asp.net core application with code first, code first approach in asp.net core, entity framework core in asp.net core,migration in asp.net

Then select ASP.NET Core Web Application. Click on the Next button.
asp.net core application with code first, code first approach in asp.net core, entity framework core in asp.net core,migration in asp.net
Enter your project Name. Click on the Create button.

asp.net core application with code first, code first approach in asp.net core, entity framework core in asp.net core,migration in asp.net

Create a new ASP.NET Core Web Application will open. Here I select MVC Application(Model-View-Controller). Click on the Create button.

asp.net core application with code first, code first approach in asp.net core, entity framework core in asp.net core,migration in asp.net


Then your project will open. 

Step:3
Now we will start the code-first entity framework setting. Create a model class "Country.cs" file inside the Model. This model class is representing the table structure.  Follow the code:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace CodeFirstApp.Models
{
    [Table(name:"Country")]
    public class Country
    {
        [Key]
        [Column(TypeName ="bigint")]
        public long Id { get; set; }
        [Column(TypeName ="varchar(50)")]
        public string Name { get; set; }
    }
}

Step:4
Create a context class "ApplicationDbContext.cs" file inside the Model. Context class gathers details about the application's entity types and how they map to a database schema. This process can be automatic as long as the tool can easily create the DbContext in such a way that it will be configured similarly to how it would be configured at run-time.  Follow the code:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CodeFirstApp.Models
{
    public class ApplicationDbContext:DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.EnableSensitiveDataLogging();
        }
        public DbSet<Country> countries { get; set; }
        public DbSet<State> states { get; set; }
    }
}

This class contains all the model’s information such as the connectionstring, database provider etc.

  • DbContext class is used for to interact with the underlying database.(i.e. to manage the database connection as well as also used to perform CRUD operation within the underlying database)
  • DbContextOptions carry all the required configuration information such as the connectionstring, database provider etc.
  • OnConfiguring method which is designed to be overridden so that you can provide configuration information for the context via the method's DbContextOptionsBuilder parameter.
  • EnableSensitiveDataLogging() Enables application data to be included in exception messages, logging, etc. This can include the values assigned to properties of your entity instances, parameter values for commands being sent to the database, and other such data.

Step:5
Open your "appsettings.json" file. Then Write Your Database provider connectionstring inside “appsettings.json” file.

"ConnectionStrings": {
"DevConnection": "Server=(local)\\SQLEXPRESS;Database=DB_Profile;Trusted_Connection=True;MultipleActiveResultSets=True"
}


Step:6
Configure your connectionstring in DbContext class inside Startup.cs class:

services.AddDbContext<ApplicationDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("DevConnection"));
});

Step:7
Migration:
Open your Package Manager Console from Tools-> Nuget Package Manager. Run the following command in the Package Manager Console.

PM> Add-Migration migrationname

This command scaffold a migration to create the initial set of tables for your model. When it is executed successfully, then run the following command.

PM> Update-Database

It will apply the new migration to the database. Now you can use SQL Server database to insert, delete, and update data.

In this way, you can implement your code-first entity framework core in asp.net core web applications.

That's it. I hope you have found this article helpful. Do let me know via comments and likes.

Video Reference:


Post a Comment

4 Comments

  1. This blog post provides useful information on ASP.NET development services offered by the agency. You have highlighted the agency's expertise, quality assurance, and client satisfaction. A great resource for businesses looking for reliable .Net development services. Thank you for sharing, If you want to Hire dedicated ASP.NET Developers India, please contact us, and we will be happy to help you.

    ReplyDelete
  2. This blog post provides useful information on ASP.NET development services offered by the agency. You have highlighted the agency's expertise, quality assurance, and client satisfaction. A great resource for businesses looking for reliable .Net development services. Thank you for sharing, If you want to Hire dedicated ASP.NET Developers India, please contact us, and we will be happy to help you.

    ReplyDelete