Code First Method in C# .NET 8 Entity Framework Core
There are 3 approach to deploy data from database to api
One is Code First.in here we first create data model and create and update database later
- Create Project with Employee Controller
- Here we create the Data Model
public class Employee_Personal
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Employee_First_Name{ get; set; }
[Required]
[MaxLength(50)]
public string Employee_Last_Name { get; set; }
[Required]
public DateTime DOB{ get; set; }
[Required]
[MaxLength(30)]
public string Position { get; set; }
}
Then get the connection string from App setting json and Inject to Program.cs class
"ConnectionStrings": {
"ConStrEmp": "Server=LAPTOP-2OTFH16P\\SQLEXPRESS;Database=EmployeeDb;User Id=sa;password=123;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
},
here is how to add Program.cs class
builder.Services.AddDbContext<EmployeeDbContext>(option =>
option.UseSqlServer(builder.Configuration.GetConnectionString("ConStrEmp")));
Right click one the project and select Nuget Packages
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer- for SQL Server Connection
Microsoft.EntityFrameworkCore.Tools -for Migration Commands
Then go to package manger console and type following command
add-migration "Initial release"
Format: add-migration Name
After this command database change temporarily store to Temporary folder
in order to commit this changes to database you need to use another command
update-database
case doesn't matter for these commands
here you can see the database and the table
Video link is here









Please subscribe my youtube channel also
ReplyDeletehttps://www.youtube.com/watch?v=MlAvncEV10E
My GIT Hub: https://github.com/buddhikasanjeewa
ReplyDelete