How to scaffold an existing SQL Server database using Entity Framework Core (EF Core) C#
How to scaffold an existing SQL Server database using Entity Framework Core
Step 1: Install EF Core NuGet Packages
In the Package Manager Console (in Visual Studio):
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Step 2: Scaffold the Database
Using Package Manager Console
- Open Package Manager Console in Visual Studio (Tools > NuGet Package Manager > Package Manager Console).
- Run the following command:
Step 3: Review the Generated Code
The scaffolding command will generate:
SimpleDbContext.cs: Represents your database context.- Entity Classes (e.g.,
Employees.cs): Represents your database tables as C# classes.
Example of SimpleDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace YourNamespace.Models{ public partial class SimpleDbContext : DbContext { public SimpleDbContext(DbContextOptions<SimpleDbContext> options) : base(options) { }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employee>(entity => { entity.HasKey(e => e.EmployeeID);
entity.Property(e => e.FirstName).HasMaxLength(50); entity.Property(e => e.LastName).HasMaxLength(50); entity.Property(e => e.Email).HasMaxLength(100); entity.Property(e => e.PhoneNumber).HasMaxLength(20); entity.Property(e => e.Salary).HasColumnType("decimal(10, 2)"); }); } }}
Step 4: Update appsettings.json
{ "ConnectionStrings": { "SimpleDbContext": "Server=YourServerName;Database=SimpleDB;Trusted_Connection=True;" }}
Step 5: Configure Startup.cs or Program.cs
In .NET 6+, add the following in your Program.cs file:
using Microsoft.EntityFrameworkCore;
using YourNamespace.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<SimpleDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("SimpleDbContext")));
var app = builder.Build();
// Configure the HTTP request pipeline.
app.Run();
Comments
Post a Comment