Search code examples
c#database-connectionblazor-webassembly

How to connect Blazor WebAssembly to DataBase


I recently started developing a Blazor WebAssembly app, and now I'm settling on a database connection.

All lessons and instructions say that you need to enter information into the Startup.cs file and appsettings.json, but these files are not in the project.

I do not understand. In Blazor WebAssembly, is there no way to connect to the DB?


Solution

  • Not directly. Blazor WebAssembly is a front end framework. You need to create an API controller to wrap your database connection and use HttpClient to call the api. A straight forward way to do it is to use an asp.net core web api controller wrapping an Entity Framework Core Database context.

    @inject HttpClient Http
    <template_html_here/>
        @code 
        {
             protected override async Task OnInitializedAsync()
            {
                products = await Http.GetFromJsonAsync<Product[]>("api/Products");
            }
        }
    

    Controller:

     [ApiController]
     [Route("api/[controller]")]
     public class ProductsController : ControllerBase
        {
           
            private readonly ProductsDbContext _context; // your database context
    
            public ProductsController(ProductsDbContext context)
            {
                _context = context;
            }
    
            [HttpGet]
            public IEnumerable<Product> Get()
            {
               return _context.Products.ToList();
            }
        }
    

    You can read more about blazor at https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1. And on asp.net core web APIs on https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio.