2022-09-15

 In this article i will show you how you can  can connect to a ms sql server database using EF core or Entity Framework core code first approach in visual studio 2022. This will tell how to connect to ms sql server database using EF core by code first approach. To mode the changes to db i have used add-migration command. and update migration command to commit the changes.

First create a new asp.net core 6 mvc application and install below mention packages.

Packages to install:------------------------------ Microsoft.EntityFrameworkCore.Tools Microsoft.EntityFrameworkCore.Design Microsoft.EntityFrameworkCore.SqlServer

Now we will add connection string in appsettings.json file.

"ConnectionStrings": {

"myconn": "Server=.\\SQLEXPRESS;Database=SalesDB;Trusted_Connection=True;"

}

After this we will create a contetxt class file and add the below code in a folder



using Microsoft.EntityFrameworkCore;

namespace CodeFirst.DBContext

{

public class SalesDBContext : DbContext

{

public SalesDBContext(DbContextOptions options) : base(options)

{

}

public DbSet<SalesProducts> SalesProducts { get; set; }

}

}

Now we will create a class class file which will have table fields.

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

namespace CodeFirst.DBContext

{

public class SalesProducts

{

[Key]

public int Id { get; set; }

[Column("PrductName", TypeName = "Varchar(200)")]

public string ProductName { get; set; }

public int Qty { get; set; }

public int SalesCount { get; set; }

}

}

Now open program.cs file and add the below code to register DB context class file.

var provider = builder.Services.BuildServiceProvider();

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

builder.Services.AddDbContext<SalesDBContext>(item => item.UseSqlServer(configuration.GetConnectionString("myconn")));

var app = builder.Build();

Always put your code above highlighted part of code.

Now run the below command to create migration and create the DB.

To add a migration

-----------------------------

add-migration MigrationName update-database To remove specific migration ---------------------------------------------Update-Database -Migration LastMigrationName To remove all migration ---------------------------------------Update-Database -Migration 0 To remove last migration ------------------------------------------Remove-Migration -force

One you done with executoin you get a migration folder.



Now check your SQL server DB.



DOWNLOAD

Show more