Code First Approach with Entity Framework

 1) To begin with the Code First Approach we need the below nuget packages in our Project.

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.Design
One can easily install the above packages with the nuget package manager or its command line tool.
Once installed you will get the below packages stacked in the installed window of nuget package manager


2) After nuget Package installation we can setup the connection string and our POCO entity classes.
  • We can set our connection to DB in appsettings.json file as below Snap Shot.

  • Now it's time to setup the DbContext class. You can create one normal class inheriting the DbContext class as below

  • As above SS we have declared one Normal Class inheriting DbContext class in which we have an empty constructor where we need to send DBContextOptions to the base class.
  • Below that we can declare our DbSets for required entity classes and have Default data that need to be added on Model creating.
  • Now create the Entity class as below SS.

  • After the above code activity, we can add DbContext Service to the Program.cs Basically it is a dependency configuration for the DbContext Class.

3) Once all above steps are done we are ready to initiate the DB migration. To add Migration execute below commands in Package Manager Console sequentially to generate Migration and Updating the database.
  • Add-Migration Initial_Migration
  • Update-Database
The First command will generate the Migration and data configuration for our POCO class and after it and be moved to database side with second command.
Whenever  we add any new entity or data items we need to follow above commands to move the things on database side.

This is how the code-first approach is used for the generating database and its table entities.
Get the Project Code on Github.

Comments

Popular posts from this blog

Getting Ready for Python Development on Ubuntu using VSCode

Designing Model class with validation in ASP.NET MVC