DEV Community

Mrunal Meshram
Mrunal Meshram

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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.

Image description

2) After Nuget Package installation we can set up the connection string and our POCO entity classes.

We can set our connection to DB in appsettings.json file as below Code Snippet.

"ConnectionStrings": {
    "DefaultDbConnection": "Data Source=.;Database=Crud_Database;Integrated Security=True;Trust Server Certificate=True"
  }   
Enter fullscreen mode Exit fullscreen mode

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

using Microsoft.EntityFrameworkCore;

namespace Crud_Operation_MVC.Models
{
    public class EntityDbContext : DbContext
    {
        public EntityDbContext(DbContextOptions<EntityDbContext> options) : base(options) { }
        public DbSet<DataEntity> DataEntities { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<DataEntity>().HasData(new DataEntity {Id = 1, Name = "Monster" },
               new DataEntity { Id = 2, Name = "Ghost" });
        }

    }
} 
Enter fullscreen mode Exit fullscreen mode

As the above code snipet, we have declared one Normal Class inheriting the DbContext class, which has an empty constructor where we need to send DBContextOptions to the base class.
Below that we can declare our DbSet List for required entity classes and have Default data that need to be added on Model creation.

Now create the Entity class as below Code Snippet.


using Microsoft.EntityFrameworkCore;

namespace Crud_Operation_MVC.Models
{
    [PrimaryKey(nameof(Id))]
    public class DataEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Code Snippet for EntityDbContext Dependency Middleware:

  // Add services to the container.
            builder.Services.AddControllersWithViews();
            builder.Services.AddDbContext<EntityDbContext>(options => 
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultDbConnection")));

Enter fullscreen mode Exit fullscreen mode

3) Once all the above steps are done we are ready to initiate the DB migration. To add Migration execute the below commands in the Package Manager Console sequentially to generate Migration and Updating the database.

`Add-Migration Initial_Migration
Update-Database`
Enter fullscreen mode Exit fullscreen mode

The First command will generate the Migration and data configuration for our POCO class and after it will be moved to the database side with the second command.
Whenever we add any new entity or data items we need to follow the above commands to move the entities(for creating tables and their relations.) on the database side.

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

Top comments (0)