How to Use Entity Framework Core Database First Approach in Asp.net Core

Entity Framework is a popular ORM (Object Relational Mapping) Framework from Microsoft .Net Ecosystem. Basically, an ORM is a technique that helps to query or manipulate data of your database in an Object-Oriented pattern.

Entity Framework an improvement of the ADO.NET ORM framework which is also from the .NET Ecosystem which gives us many advantages like lazy loading, query translation so that developers had to least bother of handling data in their application and focus more on the business logic of the application.

Entity Framework Core is the latest ORM which is a lightweight, extensible, open-source, and cross-platform version of Entity Framework which is specifically designed for ASP.Net Core Application.

In this article, we will basically check how we can set up Entity Framework Core in an ASP.NET Core Application using Database First approach.

Entity Framework provides many approaches and among them, Database First approach is the most popular approach.

I am using Visual Studio 2019 Community Version which is free to create an ASP.NET Core Web application like below


Give a project name and create a project like below


Once you create the project you need to install Entity Framework Core in your machine using the below command

dotnet tool install --global dotnet-ef


Once you installed Entity Framework Core in your machine you need to install the following packages in your application from NuGet.

  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer

packages_entity_framework_core.jpg


Please note I am using SQL Server as a relational database therefore I required Microsoft.EntityFrameworkCore.SqlServer package and if you are using some different database like Oracle PL/SQL or My SQL then you may require a different package.

In this demo, I am using AdventureWorks sample Database provided by Microsoft.

Next to create a basic structure to use Entity Framework Core in your project you need to navigate to the project folder and run the following command using command prompt

dotnet ef dbcontext scaffold "Data Source=DESKTOP-TJHLDSD\SQLEXPRESS;Initial Catalog=AdventureWorks2014;Integrated Security=true;" Microsoft.EntityFrameworkCore.SqlServer  --context-dir EFDbContext --output-dir EFDbContext --context DbCoreContext --force --table [HumanResources].[Employee]

In the above command, you need to replace the connection string with your connection string mentioned in double-quotes. Also, It's mentioned a single table i.e. HumanResources.Employee but you can mention as many tables required in your application.

basic_entityframework_command.jpg


As you can note in the above screenshot project will Build first and if Build succeeded then only it will execute successfully otherwise it will skip the creation of Entity Framework classes in your project folder.

Once the above command executes successfully I will create a folder named "EFDBContext" and required classes like below

entity_framework_core_dbcontext_created.jpg


There are two classes created, the first is DbCoreContext which will be used to access the Database, and the second is the Employee class which is created for the table Employee in your database.

Let's use this DbCoreContext class to do some basic operations.

First Add Connection string in appsettings.json file like below

 "ConnectionStrings": {
    "DbConn": "Data Source=DESKTOP-TJHLDSD\\SQLEXPRESS;Initial Catalog=AdventureWorks2014;Integrated Security=true;"
  }

Second, configure DbContext in ConfigureServices method in Startup.cs file

 services.AddDbContext<DbCoreContext>(options =>
                            options.UseSqlServer(Configuration.GetConnectionString("DbConn")));


configure_dbcontext_ef_core.jpg


Third, we need to inject DbCoreContext in the Controller class like below

private readonly DbCoreContext _dbCoreContext;
public HomeController(ILogger<HomeController> logger, DbCoreContext dbCoreContext)
        {
            _logger = logger;
            _dbCoreContext = dbCoreContext;
        }

inject_dbcorecontext_controller.jpg


Now we can use DbCoreContext to get the data from DB using Lambda or LINQ Query.

var maleEmployees = _dbCoreContext.Employees.Where(x => x.Gender == "M").ToList();

final_result_efcore.jpg

Hope you understood how to set up Entity Framework Core in the ASP.Net Core application using Database First approach.

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee