asp.net-core - Blazor 应用程序中的数据检索返回空数组

标签 asp.net-core blazor blazor-server-side

我目前正在努力创建我的第一个 Blazor 项目,该项目应该是一个小型 CRUD 应用程序。我尝试遵循一些教程,但大多数都是过时的预发布教程,并且有许多差异让我感到困惑。

我的问题是我还不理解一些基本概念(尤其是“服务”)。当我启动应用程序时,出现以下错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Temporary local of type 'UserManagement.Models.Users[]> was null.

错误发生在 Index.razor 中的“@foreach (var user in users)”行。我会理解没有检索到数据。但是,我的用户表中有数据。所以我真的不知道错误可能在这里。

到目前为止我们所拥有的是:

索引.razor

@page "/"
@using Models
@using Data
@inject UserService us

<form method="post">
    <input asp-page="/Create" type="button" value="Neuen Benutzer erstellen" />
</form>

<form method="post">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>UserID</th>
                <th>Name</th>
                <th>Supervisor</th>
                <th>Ersteller</th>
                <th>Erstelldatum</th>
                <th>Optionen</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var user in users)
            {
                <tr>
                    <td>@user.PkId</td>
                    <td>@user.UserId</td>
                    <td>@user.FirstName @user.LastName</td>
                    <td>@user.Supervisor</td>
                    <td>@user.CreationUser</td>
                    <td>@user.CreationDate</td>
                    <td>
                        <a>Delete Account</a><br />
                        <a asp-page="/Edit"> Edit Account</a>
                    </td>
                </tr>
            }
        </tbody>

    </table>
</form>

@code {

    Users[] users;

    protected override async Task OnInitializedAsync()
    {
        users = await us.GetUsersAsync();
    }
}
}

UserService.cs

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using UserManagement.Models;

namespace UserManagement.Data
{
    public class UserService
    {
        private static  UserManagementContext _context;

        public UserService (UserManagementContext context)
        {
            _context = context;
        }

        public async Task<Users[]> GetUsersAsync()
        {
            Users[] u;
            u = await _context.Users.ToArrayAsync();
            return u;

        }
    }
}

模型:Users.cs

using System;
using System.Collections.Generic;

namespace UserManagement.Models
{
    public partial class Users
    {
        public int PkId { get; set; }
        public int FkJobtitle { get; set; }
        public int FkCostcenter { get; set; }
        public int? FkLocation { get; set; }
        public int? FkDepartment { get; set; }
        public int? FkWorkplace { get; set; }
        public int? FkLanguage { get; set; }
        public string UserId { get; set; }
        public string Salutation { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PersonalId { get; set; }
        public string Supervisor { get; set; }
        public string Telephone { get; set; }
        public DateTime ValidFrom { get; set; }
        public DateTime CreationDate { get; set; }
        public string CreationUser { get; set; }
        public DateTime? ModificationDate { get; set; }
        public string ModificationUser { get; set; }

        public virtual CostCenter FkCostcenterNavigation { get; set; }
        public virtual Department FkDepartmentNavigation { get; set; }
        public virtual Jobtitle FkJobtitleNavigation { get; set; }
        public virtual Language FkLanguageNavigation { get; set; }
        public virtual Location FkLocationNavigation { get; set; }
    }
}

当然还有支架DbContext(摘录):

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace UserManagement.Models
{
    public partial class UserManagementContext : DbContext
    {
        public UserManagementContext()
        {
        }

        public UserManagementContext(DbContextOptions<UserManagementContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Approver> Approver { get; set; }
        public virtual DbSet<Branche> Branche { get; set; }
        public virtual DbSet<CostCenter> CostCenter { get; set; }
        public virtual DbSet<DealerCompany> DealerCompany { get; set; }
        public virtual DbSet<Department> Department { get; set; }
        public virtual DbSet<Jobtitle> Jobtitle { get; set; }
        public virtual DbSet<Language> Language { get; set; }
        public virtual DbSet<Location> Location { get; set; }
        public virtual DbSet<Request> Request { get; set; }
        public virtual DbSet<RequestTypes> RequestTypes { get; set; }
        public virtual DbSet<SystemRole> SystemRole { get; set; }
        public virtual DbSet<SystemType> SystemType { get; set; }
        public virtual DbSet<Systems> Systems { get; set; }
        public virtual DbSet<Users> Users { get; set; }
        public virtual DbSet<Workplace> Workplace { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
.....

在我的启动中,我必须使用 services.AddTransient 而不是 AddSingleton 来加载 UserService,因为后者会遇到以下错误:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: UserManagement.Data.UserService Lifetime: Singleton ImplementationType: UserManagement.Data.UserService': Unable to resolve service for type 'UserManagement.Models.UserManagementContext' while attempting to activate 'UserManagement.Data.UserService'.)'

最佳答案

当组件被渲染时,它会尝试在OnInitializedAsync()之前创建 View 。被执行。 它为您提供 null ref exc,因为它尝试渲染页面,并且 foreach 调用数组迭代器的 NextItem(),但数组为 null。

index.razor中的解决方案初始化ctor中的数组或将声明更改为: Users[] users = new Users[x];其中 x 是要存储在列表中的元素数量。 对于灵活的解决方案,我建议使用 List 而不是数组。 List<User> users = new List<User>();

关于asp.net-core - Blazor 应用程序中的数据检索返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58305568/

相关文章:

Blazor InputFile 重置/清除值 - statehaschanged() 不起作用

c# - 验证在 Blazor 服务器端不起作用

c# - OrderBy 抛出无法加载文件或程序集 System.Data.Entity

c# - Asp.Net vNext 在现有应用程序中自托管

c# - 无法将项目集合呈现为 Blazor 表单

Blazor 组件生命周期方法 OnParametersSet 行为

entity-framework-core - Blazor Server 组件之间的数据库上下文保持一致

ssl-certificate - 信号R : The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

c# - 从.net core中的layout.cshtml访问数据库

asp.net-core - 复制时出现 ASP.NET Core 2.1 Hangfire 错误