Create Crud Application Using Code First Approach in Asp.net 6
Create a New Project: Open Visual Studio and create a new ASP.NET Core Web Application. Choose the "ASP.NET Core Web App" template, select the appropriate version (ASP.NET Core 6 in your case), and choose the "Web Application" template.
Install Entity Framework Core: Right-click on your project in Solution Explorer, select "Manage NuGet Packages," and install the
Microsoft.EntityFrameworkCore.SqlServer
package.Create Model: Create a
Student
class in theModels
folder:using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CodeFirstAproch.Models { public class Student { [Key] public int ID { get; set; } [Column("StudentName", TypeName ="varchar(100)")] public string Name { get; set; } [Column("StudentGender", TypeName ="varchar(100)")] public string Gender { get; set; } public int Age { get; set; } [Column("StudenStandard", TypeName ="varchar(50)")] public string Standard { get; set; } } }
DbContext: Create a
DbContext
class in theData
folder:using Microsoft.EntityFrameworkCore; namespace CodeFirstAproch.Models { public class StudentDbContext : DbContext { public StudentDbContext(DbContextOptions options) : base(options) { } public DbSet<Student> Students { get; set; } } }
Configure DbContext in Startup: In the Program.cs file, configure the DbContext in the
ConfigureServices
method:"ConnectionStrings": { "conne": "Server=DESKTOP-R3TAG3F\\SQLEXPRESS;Database=CodeFirstAproach;Trusted_Connection=True;TrustServerCertificate=True;" },
Ensure you have a connection string named "conne" in your
appsettings.json
file.Controller and Views: Right-click on the
Controllers
folder, select "Add" -> "Controller," choose "MVC Controller with views, using Entity Framework," select yourStudent
model, and choose yourApplicationDbContext
.Apply Migrations and Update Database: Open Package Manager Console set the default project to your web project, and run:
Add-Migration InitialCreate Update-Database
Run the Application: Press
F5
or click on the "Start Debugging" button to run your application. Visithttps://localhost:5001/Students
your browser to see the CRUD operations.
These steps assume you have Visual Studio and the necessary SDKs installed. Adjust the steps based on your specific project structure or requirements.