Blazor Helpers App: Entity Framework Summary
January 30, 2021 17:38
David Jones MVP
blazor
blazor
entity-framework
csharp
blazor-server
30 Jan 2021 17:38:57
David Jones MVP
blazor blazor entity-framework csharp blazor-server
blazor blazor entity-framework csharp blazor-server
A summary of the steps for setting up a database using Entity Framework Core via Code First
This is a summary of the steps in previous post.
- Create a Blazor Service app with Identity through local data
- This is to get an ApplicationDbContext. You could get DbContext without this though.
- Setup the database connectivity through a connection string in appsettings.json. Default is an .mdf file.
- Create the database using
update-database
- Create a class for each entity with an Id and other properties and each with suitable annotations.
- Class instances can be properties of another class.
- No need for the referenced class Id in the consuming class. Nb: EF uses the Id in database though.
- Each Entity needs a DbContext.
- Run
add-migration
Thenupdate-database
- Repeat the previous 2 steps every time you add, delete or modify the entity classes.
- Create a Service class to access the database with or without an interface.
- This implements database CRUD through the DbContext.
- If using an interface add, for example, the following to startup.cs in ConfigureServices()
services.AddTransient<IHelperService, HelperService>();
- If not add, for example:
services.AddTransient<HelperService>();
- If not add, for example:
- The Add method can be AddScoped, AddTransient or AddSingleton .. more on that in a subsequent post.
- In a razor page inject an instance of the service using:
@inject IHelperService service
if using an interface with the service OR
@inject HelperService service
if not using an interface! - Then in the page’s codebehind use service.<CRUD methods in the service>()
Topic | Subtopic | |
This Category Links | ||
Category: | Blazor Index: | Blazor |
Next: > | Blazor Helpers App | EF Migrations and CRUD Operations |
< Prev: | Blazor Helpers App | An Entity Framework Primer |