Steps of Code First Entity
Step 01:
- INSTALL PACKAGES (Microsoft.EntityFrameworkCore.Design, Microsoft.EntityFrameworkCore.Tools, Microsoft.EntityFrameworkCore.sqlserver)
Step 02:
CREATE MODEL (Example. STUDENT.CS EMPLOYEE.CS)
ADD THE PROPERTY IN MODEL (INT ID, STRING NAME, STRING MOBILE)
// [Key] -- Primary Key Atrribute
// [Column("StudentNumber", TypeName="varchar(15)")] -- Specifying Column Name using the Column Attribute
- CREATE DB CONTEXT CLASS IN MODEL (Example. STUDENTDBCONTEXT.CS
- Paste This Code or Follow This Code
public class StudentDbContext //your DBcontext model name: DbContext
{
public StudentDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Student //your model name> Student //create sql table name{ get; set; }
}
Step 03
Create a Connection String in appseting.json
{
"ConnectionStrings": {
"DBconnect": "Server=SERVERNAME;Database=DATABASENAME;trustServerCertificate=true;Trusted_Connection=True;"
},
} Step 04
Register the connection string in program.cs (paste this code above the app builder build)
var provider = builder.Services.BuildServiceProvider();
var config = provider.GetRequiredService<IConfiguration>();builder.Services.AddDbContext<StudentDbContext//your DBcontext model name>(item => item.UseSqlServer(config.GetConnectionString("DBconnect")));
Step 05
Add the migration
tools>NuGet Package Manager>Package Manager Console
add-migration CodeFirstCreateDB //create migration name
Press Enter
update-database
Press Enter