Monday, 13 January 2025

EF Core 9 Generate Code First from Existing DB

1.Install EF Core, EF core Design, EF sql server using nuget packages.

2. Open package manger console 

3. Select the project where need to place entity and DbContext

4.Run below comments with modified inputs which is highlighted.

dotnet ef dbcontext scaffold "Server={Server};Database={DBname};User Id={db user name};Password={PWD};Encrypt=True;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer --output-dir DbEntity --context-dir DbContext --context CoreDbContext --use-database-names --force --project D:/Source_vs2022/Core.Data/Core.Data.csproj

5. Now we can see Db context and db entity



6.Migrate to Full Code-First

If you want to start using migrations with the generated context execute below in same package mager console.

  1. Add migrations:
    dotnet ef migrations add InitialCreate --project Core.Data
  2. Update the database:
    dotnet ef database update --project Core.Data --verbose
Where :
  • InitialCreate is migration name
  • Core.Data is pr
NOTE: 
  • In case any other error occurs like missing OnConfigure then add below code in DBContext file.
  • after migration generated remove it below code due to security reason.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server={DB-Server};Initial Catalog={DB};User ID={UserName};Password={PWD};");
    }
}


No comments:

Post a Comment