Example of a Blazor WebAssembly project that uses Entity Framework Core on the server for data access.
ARCHIVED 2025-02-06
Example of a Blazor WebAssembly project that uses Entity Framework Core on the server for data access.
Do you prefer Blazor Server instead? No problem! The same project is implemented for server here.
I created this series of blog posts to explain the project in detail (note: series is valid up to commit
e6ac27b):
For the latest version, read about the latest round of refactoring here:
🙏 Thanks to John Barrett for helping identify initial issues.
IHttpClientFactory
to create a custom client with an authorization message handlerClone the repository (or your fork):
git clone https://github.com/jeremylikness/BlazorWasmEFCoreExample.git
localdb
installed, update appsettings.json
and appsettings.Development.json
in the ContactsApp.Server
project to point to a valid database instance. DefaultConnection
is used for identity and can have any database name.blazorcontactsdb
is used for the application database and must match ContactContext.BlazorContactsDb
in the ContactsApp.DataAccess
project (the default value is blazorcontactsdb
).ContactsApp.Server
project is set as the start up project.NuGet Package Manager -> Package Manager Console
. In the console, with the server project selected, create the identity migration by typing:
Add-Migration -Context ApplicationAuditDbContext Initial
After it is complete, apply the migration:
Update-Database -Context ApplicationAuditDbContext
See note at the end of the next section.
ContactsApp/Server
folder.Run
dotnet ef migrations add --context ApplicationAuditDbContext Initial
to set up the identity database migrations.
Run
dotnet ef database update --context ApplicationAuditDbContext
to create the identity database.
Type
dotnet run
to start the server. Navigate to the port specified.
Note: the demo app is designed to create and populate the contacts database the first time you open the web page. This may result in a delay of up to several minutes on first load. This is normal and is just used to make setup easier. Subsequent runs should load faster.
The context for contacts (ContactContext
) resides in the ContactsApp.DataAccess
assembly. It is a .NET Standard class library and cannot be executed directly. I created a ContactContextFactory
in the ContactsApp.Server
project to enable migrations by using the SQL Server provider and loading the connection string. To create a migration, you must specify the executable startup project and the context name. This command will create a migration in the Migrations
folder named InitialContact
(assuming this is run from the root of the solution directory):
dotnet ef migrations add --startup-project ContactsApp/Server --context ContactContext InitialContact
Use the --namespace
parameter to specify a different namespace to help avoid conflicts with the identity context.
Submit any feedback, questions, suggestions, or issues here.
Regards,