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.
"ConnectionStrings": { "myconn":
"Server=.\\SQLEXPRESS;Database=SalesDB;Trusted_Connection=True;" } |
using
Microsoft.EntityFrameworkCore;
namespace CodeFirst.DBContext { public class SalesDBContext :
DbContext { public SalesDBContext(DbContextOptions
options) : base(options) { } public DbSet<SalesProducts>
SalesProducts { get; set; } } } |
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; } } } |
var provider =
builder.Services.BuildServiceProvider(); var configuration =
provider.GetRequiredService<IConfiguration>(); builder.Services.AddDbContext<SalesDBContext>(item => item.UseSqlServer(configuration.GetConnectionString("myconn"))); var
app = builder.Build(); |
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
0 comments:
Please let me know your view