Create Web Api with Entity Framework Core DB First
DBFirst Approach always create database first and then automatically create model from db
- First Create Database and Create Table with Any Name Eg:EmployeePersonalData
Then go to appsettings.json and put the connection string
"ConStr": "Server=LAPTOP-2OTFH16P\\SQLEXPRESS;Database=EmployeeDb;User Id=sa;password=123;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
- Server: SQL server Name
- Database:Db Name
- Trusted_Connection need for HTTPS
- TrustServerCertificate=True also compulsory for HTTPS
Then Right Click on Nuget Packages and install below packages
below 3 packages are compulsory and should be same version and stable version
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
Then Execute Below command in Nuget Package Manger Console
Fomat
Scaffold-DbContext ConnectionString Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Eg:
Scaffold-DbContext 'Name=ConnectionStrings:Constr' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Microsoft.EntityFrameworkCore.SqlServer is provider name
OutputDir means project folder which creates model
After execute this you can see folder called "Models" in your project and some cs files
In that folder you can see DbContext file
Format: Dbname +DbContext
Eg:EmployeeDbContext
in this one connection string is hardcorded it is not good practice
so we should take connection string from config file
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("ConStr"));
then we have add this connection to Program.cs file as Middelware
object value = builder.Services.AddDbContext<EmployeeDbContext>(option =>
option.UseSqlServer(builder.Configuration.GetConnectionString("ConStr")));
Then you can refer this context class from any class and use for CRUD operations
Then Press Ctrl +F5 and run the web application
here is Video Link of this tutorial











Comments
Post a Comment