Header Ads Widget

Responsive Advertisement

Ticker

6/recent/Apple

Code First Entity

 

Step 1: Install Necessary Packages

First, you need to install the following packages:

1. Microsoft.EntityFrameworkCore.Design
2. Microsoft.EntityFrameworkCore.Tools
3. Microsoft.EntityFrameworkCore.SqlServer

You can install these packages using the NuGet Package Manager in Visual Studio or by running the following commands in the Package Manager Console

Step 2: Create the Model

Create your model classes. For example, let's create a `Student` class.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class Student
{
    [Key]
    public int ID { get; set; }
    
    [Column("StudentName", TypeName = "varchar(50)")]
    public string Name { get; set; }
    
    [Column("StudentMobile", TypeName = "varchar(15)")]
    public string Mobile { get; set; } 
}
Step 3: Create the DbContext Class
Create a DbContext class that will manage the entity objects during runtime, including populating objects with data from a database, change tracking, and persisting data to the database.
using Microsoft.EntityFrameworkCore;

public class StudentDbContext : DbContext
{
    public StudentDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet Students { get; set; }
}

Step 4: Create the Connection String in `appsettings.json`

Add your database connection string in the `appsettings.json` file.

{
  "ConnectionStrings": {
    "DBconnect": "Server=YOUR_SERVER_NAME;Database=YOUR_DATABASE_NAME;TrustServerCertificate=true;Trusted_Connection=True;"
  }
} 
Step 5: Register the Connection String in `Program.cs`
Register the DbContext in your `Program.cs` file. Add the following code before building the app.

var provider = builder.Services.BuildServiceProvider();
var config = provider.GetRequiredService();

builder.Services.AddDbContext(options =>
    options.UseSqlServer(config.GetConnectionString("DBconnect"))); 

Step 6: Add the Migration

Open the NuGet Package Manager Console and run the following commands to add a migration and update the database:

Add-Migration MigrationName
Update-Database
 



Post a Comment

0 Comments