1. Install necessary packages:
For a Blazor Server App, you’d typically manage the EF Core functionality in the Server project. So, make sure you are working in the Server project directory or set the Server project as the default project in the Package Manager Console (PMC) in Visual Studio.
Using the NuGet Package Manager or the PMC, install the following packages:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
(for migration tools)
2. Define your Model:
Create classes that will define the structure of your database tables. Place these in the Shared or Server project, depending on your design decisions.
Example:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
3. Create a DbContext:
In the Server project, create a class that derives from DbContext
:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
4. Configure the Connection String:
In the appsettings.json
file in the Server project, add your connection string:
{ "ConnectionStrings": { "DefaultConnection": "
Server=Servername;Database=DatabaseName;user=UserId;password=secret;MultipleActiveResultSets=true;TrustServerCertificate=True;MultiSubnetFailover=True" } }
Replace YourConnectionStringHere
with your MS SQL Server 2022 connection string.
5. Register DbContext:
In the Startup.cs
(or Program.cs
for newer versions) of your Server project, register the DbContext
in the ConfigureServices
method:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
(Do not forget to import EF Core)
6. Create Initial Migration:
In the PMC or terminal, navigate to the Server project directory and run:
Add-Migration InitialCreate
This will scaffold a migration to create the initial set of tables for your model.
7. Update the Database:
Apply the migration to create the database schema:
Update-Database
8. Use the DbContext in your app:
Now you can inject and use your DbContext
in your pages, components, or services:
csharpCopy code@inject AppDbContext _context
// ...
var products = await _context.Products.ToListAsync();
That’s the basic setup! As your app grows, you might add more entities, relationships, migrations, and other advanced EF Core features. Ensure you understand concepts like the lifecycle of a DbContext and how it tracks changes to entities to avoid issues when manipulating data.