A HowTo on setting up a Blazor Server App using Entity Framework Core to connect to an SQL Server Database using Code First.

The complete solution is available on GitHub at : https://github.com/djaus2/EFBlazorBasics.

An index to the blog posts here in this series: Blazor Helper App

Creating the Project

  1. In Visual Studio create a new Blazor App, choose Server option, leave https enabled and choose Authentication (Change).

  2. For Authentication choose Individual User Account and accept the default of Store user accounts in the app. When the app setup is complete this will implement tables in a SQL Database for handling user identity.

  3. Note contents under the Data folder in Solution Explorer:

    • ApplicationDbContext.cs file
    • Migrations Folder
  4. Have a look at the files in the Migrations folder, in particular the snapshot file.

    • Note the Model Builder code to build the various User Identity Tables
    • Look at appsettings.json and the provision of a ConnectionString to a local database for these User Identity tables.
  5. The app will fail if you run it at this stage because the database hasn’t been created yet. Try it

Database Creation

  1. In Tools–>Manage Nuget Packages–>Package Management Console (PMC) run:

    update-database

  2. Run the app now and Register

    • Note that the database was created as an .mdf file

    By default, LocalDB database creates “*.mdf” files in the C:/Users/<username> directory.
    It will have a filename of the format aspnet-<project name>-<a guid>.mdf There is a _log.ldf file as well.

  3. In appsettings.json, change the ConnectionString to use SQLServer Express as follows:

     "ConnectionStrings": {
     "DefaultConnectionMDF":
     "Server=(localdb)\\mssqllocaldb;Database=aspnet-BlazorApp10-425CFE5B-2F11-411E-A5BA-6A10D3F9365E;Trusted_Connection=True;MultipleActiveResultSets=true",
    
     "DefaultConnection": "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Helpers;Integrated Security=SSPI;"
     },
    
    • The Catalog is the database name and can be anything suitable, Helpers in this case.
  4. Repeat step 1 again. (update-database)

    • If you have SQL Server Management Studio, run that and connect to SQLExpress locally. Open the database as named and examine the tables.

    • Alternatively connect via Server Explorer in Visual Studio

  5. Run the app again, Register and view your registration in the dbo.AspNetUsers table as per 2.

Entities

  1. Add one or more classes as entities to the app, as discussed in the previous post:

    • For example, add the following as class file in the Data folder:
     public class Helper
     {
         [Key]
         [Column("Id")]
         public int Id { get; set; }
    
         ... More ...
     }
    

    The complete file is Activity.cs here on GitHub

  2. Add a new service for example as follows, as a new class in the Data folder or a new Services folder.

     public interface IDataAccessService
     {
         ...
     }
     public class DataAccessService : IDataAccessService
     {
         private readonly ApplicationDbContext _context;
         public DataAccessService(ApplicationDbContext context)
         {
            _context = context;
         }
         public async Task\<List\<Activity\>\> GetActivitys()
         {
              ... More ...
         }
     }
    
    

    The complete file is HelperService.cs here on GitHub

  3. Add an entry in startup.cs (Look for the WeatherForecastService entry and put it under that:

         services.AddTransient<IHelperService, HelperService>();
    
  4. In Package Management Console (PMC):

    Run add-migration AddEntities
    Then update-database

     PM> add-migration AddEntities
     Build started...
     Build succeeded.
     To undo this action, use Remove-Migration.
     PM> update-database
     Build started...
     Build succeeded.
     Done.
     PM>
    
  5. Inspect the database again and view the three new tables

  6. Again run the app to check that all is still OK.

Checking Database Access

Now to test the database access from the app. Only test that the mechanism works. We have no data.

  1. In the FetchData.razor page add the following near the top just after the @inject WeatherForecastService ForecastService line:

         @inject IHelperService service
    

    An important note: This got me for some time before I realised. I’ve seen discussion of this runtime error but not with this solution. If you insert \@inject HelperService service it will fail at runtime when you try to access the data. This is because the service above was added with the interface and the registered service name is IHelperService, not HelperService. You will get a message like:

     Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost: Error: Unhandled exception in circuit  
     'EGaiqQkFImk26uEUdm0aTl0QIU_Xhy4TqWk6qRzJmpw'.
    
     System.InvalidOperationException: Cannot provide a value for property 'service' on type 'EFBlazorBasics.Pages.FetchData'.  
     There is no registered service of type 'EFBlazorBasics.Data.HelperService'.
    

    Forewarned is Forearmed!

  2. In the FetchData.razor page in OnInitializedAsync(), just below the forecasts= line add:

         var activitys = await service.GetActivitys();
    
  3. Set a breakpoint just after that line, run the app and select the FetchData page.
    See that the app runs OK and activitys is a not null but a list of zero length. We haven’t added any data.

All is OK. The database access using Entity Framework has worked!


Next: A Summary of the above and adding some data.


 TopicSubtopic
   
 This Category Links 
Category:Blazor Index:Blazor
  Next: > Blazor Helpers App
<  Prev:   Blazor Helpers App