简体   繁体   English

如何将 Blazor 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.我最近开始开发 Blazor WebAssembly 应用程序,现在我正在解决数据库连接问题。

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.所有课程和说明都说您需要在 Startup.cs 文件和 appsettings.json 中输入信息,但这些文件不在项目中。

I do not understand.我不明白。 In Blazor WebAssembly, is there no way to connect to the DB?在 Blazor WebAssembly 中,有没有办法连接到数据库?

Not directly.不直接。 Blazor WebAssembly is a front end framework. Blazor WebAssembly 是一个前端框架。 You need to create an API controller to wrap your database connection and use HttpClient to call the api.您需要创建一个 API 控制器来包装您的数据库连接并使用 HttpClient 来调用 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.一个直接的方法是使用包装实体框架核心数据库上下文的 asp.net 核心 web api 控制器。

@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://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1 .您可以在https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1阅读有关 blazor 的更多信息。 And on asp.net core web APIs on https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio .https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio上的 asp.net 核心 Web API 上。

If you are referring to local storage (browser storage) then this component by Chris Sainty could help you.如果您指的是本地存储(浏览器存储),那么Chris Sainty 的这个组件可以帮助您。

However if you are looking for a connection to a Database like a SQL Server or document storage like Mongo it can not be done directly.但是,如果您正在寻找与 SQL Server 等数据库或 Mongo 等文档存储的连接,则无法直接完成。

Blazor Wasm is for front end development. Blazor Wasm 用于前端开发。 You will need to call web APIs that connect to databases stored on servers.您将需要调用连接到存储在服务器上的数据库的 Web API。

It is now 2022. .NET 6 has shipped, and Blazor WebAssembly has support for compiled binaries.现在是 2022 年。.NET 6 已经发布,并且 Blazor WebAssembly 支持已编译的二进制文件。

That means there are now three options for using a database in a Blazor WebAssembly application.这意味着现在有三个选项可用于在 Blazor WebAssembly 应用程序中使用数据库。

#1. #1。 Create a webApi.创建一个 webApi。 Call the webApi on from the client as you can see being done in the default sample.正如您在默认示例中看到的那样,从客户端调用 webApi。 See FetchData.razor请参阅 FetchData.razor

protected override async Task OnInitializedAsync()
{
    forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}

and WeatherForecastController.cs on the server.和服务器上的 WeatherForecastController.cs。 The default solution does not call a database, but you could easily use a dbContext in Get() to pull data from a database.默认解决方案不调用数据库,但您可以轻松地使用 Get() 中的 dbContext 从数据库中提取数据。

#2: With support for compiled binaries in Blazor WebAssembly, it is now possible to completely host Sqlite in WebAssembly. #2:通过在 Blazor WebAssembly 中对编译二进制文件的支持,现在可以在 WebAssembly 中完全托管 Sqlite。

https://github.com/TrevorDArcyEvans/BlazorSQLiteWasm https://github.com/TrevorDArcyEvans/BlazorSQLiteWasm

#3: IndexedDb. #3:索引数据库。 Through js interop, the IndexDb in the browser can be used.通过js互操作,可以使用浏览器中的IndexDb。 Large amounts of data can be stored in this Db, and like the name implies, it is indexed.大量的数据可以存储在这个 Db 中,并且顾名思义,它是被索引的。 Since this can be accidentally cleared, it is most useful in a PWA, where that is more difficult.由于这可能会被意外清除,因此它在 PWA 中最有用,因为这更困难。 Also, with this and Sqlite, anything done in the browser is open to the user and hackers that compromise the user's maching.此外,有了这个和 Sqlite,在浏览器中所做的任何事情都对用户和黑客开放,从而危及用户的机器。

I use https://github.com/wtulloch/Blazor.IndexedDB我使用https://github.com/wtulloch/Blazor.IndexedDB

You add schema in program.cs:您在 program.cs 中添加架构:

builder.Services.AddIndexedDB(dbStore =>
{
    dbStore.DbName = "SomeDbName";
    dbStore.Version = 1;
    dbStore.Stores.Add(new StoreSchema
    {
        Name = "People",
        PrimaryKey = new IndexSpec { Name = "id", KeyPath = "id", Auto = false },
        Indexes = new List<IndexSpec>
        {
            new IndexSpec{Name="alias",  KeyPath = "alias", Auto=false},
            new IndexSpec{Name="isAvailable", KeyPath = "isAvailable", Auto=false},
            new IndexSpec{Name="communityId", KeyPath = "communityId", Auto=false},
            new IndexSpec{Name="isFriend", KeyPath = "isFriend", Auto=false},
        }
    });
});

In this code, the names of the fields are camelCased, whereas the objects I'm constructing are PascalCase.在这段代码中,字段的名称是驼峰式命名的,而我正在构建的对象是 PascalCase。 This was actually necessary for me to get it to work.这实际上是我让它工作所必需的。 I think my serializer may be set to camelCase Json or something, so watch that.我认为我的序列化程序可能设置为 camelCase Json 之类的,所以请注意。

And then you add remove and search using:然后使用以下命令添加删除和搜索:

public async Task AddPersonAsync(LocalPerson member)
{
    var newPerson = new StoreRecord<LocalPerson>
    {
        Data = member,
        Storename = PeopleStoreName
    };
    await _dbManager.AddRecord(newPerson);
}
public async Task<LocalPerson> GetPersonByIdAsync(Guid id)
{
    var localPerson = await _dbManager.GetRecordById<Guid, LocalPerson>(PeopleStoreName, id);
    return localPerson;
}
public async Task<List<LocalPerson>> GetPeopleAsync()
{
    var results = await _dbManager.GetRecords<LocalPerson>(PeopleStoreName);
    return results;
}

public async Task<List<LocalPerson>> GetPeopleByCommunityAsync(Guid id)
{
    var indexSearch = new StoreIndexQuery<Guid>
    {
        Storename = PeopleStoreName,
        IndexName = "communityId",
        QueryValue = id,
    };
    var result = await _dbManager.GetAllRecordsByIndex<Guid, LocalPerson>(indexSearch);

    if (result is null)
    {
        return new List<LocalPerson>();
    }

    return (List<LocalPerson>)result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 Blazor Serverside 与 Blazor WebAssembly 结合使用? - How to use Blazor Serverside with Blazor WebAssembly? 如何访问 blazor webassembly 中的应用程序设置 - How to acess the appsettings in blazor webassembly 如何创建连接到具有 CRUD 功能的数据库的 Blazor WebAssembly 网站 - How do you create a Blazor WebAssembly website connected to a database with CRUD functions 如何在 Blazor WebAssembly-PWA 中运行离线数据库使用? - How can I run offline database usage in Blazor WebAssembly-PWA? 如何在 Blazor WebAssembly 中显示 .txt 文件的内容 - How to display content of .txt file in Blazor WebAssembly 如何在 Blazor WebAssembly 中登录时运行代码? - How to run code on login in Blazor WebAssembly? 如何在 blazor webassembly 应用程序中获取服务器 url? - How to get the server url in blazor webassembly app? 如何使用 SignInManager 为 Blazor WebAssembly 实现模拟? - How to implement impersonation using SignInManager for Blazor WebAssembly? 如何在Blazor WebAssembly项目中使用C# 9? - How to use C# 9 in Blazor WebAssembly project? 如何加载 ResponseCompressionDefaults function(Blazor WebAssembly SignalR) - how to load ResponseCompressionDefaults function (Blazor WebAssembly SignalR)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM