两个表的连接在 Razor 页面上不起作用

问题描述 投票:0回答:1

我尝试在 Razor 页面应用程序上创建一个报告页面,但无法使其工作。我有一个类似的工作应用程序,看不到我在哪里做不同的事情,但一定缺少一些明显的东西。

这是有问题的视图:

@page
@model RabiesShotTracker.Pages.Reports.UnpaidBills.IndexModel

<div id="UnpaidBillsIndex" class="container p-3">
    <div class="row pt-4">
        <div class="col-6">
            <h2 class="text-primary">Unpaid Bills</h2>
        </div>
    </div>

    <br /><br />

    <form asp-page="./Index" method="post">
        <div id="UnpaidBillsReport" class="row pt-4">
            <div class="col-25">
                <h2 class="text-primary" align="center">Public Health</h2>
                <h3 class="text-primary" align="center">Rabies Shots Unpaid Bills</h3>
            </div>
                <table id="DataTable" class="table table-bordered" style="width:75%" align="center">
                    <thead>
                        <tr>
                            <th style ="text-align: center">
                                Incident No
                            </th>
                            <th style="text-align: center">
                                Patient Name
                            </th>
                            <th style="text-align: center">
                                Date of Birth
                            </th>
                            <th style="text-align: center">
                                Exposure Date
                            </th>
                            <th style="text-align: center">
                                Date Shot Scheduled
                            </th>
                            <th style="text-align: center">
                                Date Shot Received
                            </th>
                        </tr>
                    </thead>
                    <tbody>

                        @for (var i = 0; i < Model.Client.Shots.Count; i++)
                        {
                            <tr>
                                <td style="width: 15%">
                                    <div class="mb-3">
                                        <input asp-for="Client.Shots[i].IncidentNo" type="text" readonly class="form-control-plaintext" />
                                    </div>
                                </td>
                                <td style="width: 25%">
                                    <div class="mb-3">
                                        <input asp-for="Client.FullName" type="text" readonly class="form-control-plaintext" />
                                    </div>
                                </td>
                                <td style="width: 15%">
                                    <div class="mb-3">
                                        <input asp-for="Client.Birthdate" type="text" readonly class="form-control-plaintext" />
                                    </div>
                                </td>
                                <td style="width: 15%">
                                    <div class="mb-3">
                                        <input asp-for="Client.ExposureDate" type="text" readonly class="form-control-plaintext" />
                                    </div>
                                </td>
                                <td style="width: 15%">
                                    <div class="mb-3">
                                        <input asp-for="Client.Shots[i].ShotSchedDate" type="text" readonly class="form-control-plaintext" />
                                    </div>
                                </td>
                                <td style="width: 15%">
                                    <div class="mb-3">
                                        <input asp-for="Client.Shots[i].ShotRecdDate" type="text" readonly class="form-control-plaintext" />
                                    </div>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
    </form>
</div>

这是它背后的.cs:

using RabiesShotTracker.Data;
using RabiesShotTracker.Model;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace RabiesShotTracker.Pages.Reports.UnpaidBills
{
    public class IndexModel : PageModel
    {
        private readonly ApplicationDbContext _db;

        public Client Client { get; set; }
        public Shot Shot { get; set; }


        public IndexModel(ApplicationDbContext db)
        {
            _db = db;
        }

        public void OnGet(int Id)
        {
            Client = _db.Client
                    .Include(client => client.Shots).FirstOrDefault(client => client.ClientId == Id);
        }

    }
}

这是客户端模型的相关部分:

using System.ComponentModel.DataAnnotations;

namespace RabiesShotTracker.Model
{
    public class Client
    {
        [Key]
        [Display(Name = "Client Id")]
        public int ClientId { get; set; }

        public List<Shot>? Shots { get; set; }

        [Required]
        [Display(Name = "Client No (###)")]
        public string? ClientNo { get; set; }

        [Required]
        [Display(Name = "Incident No")]
        public string? IncidentNo { get; set; }

这是镜头模型的相关部分:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace RabiesShotTracker.Model
{
    public class Shot
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int ShotId { get; set; }

        [Required]
        public int ClientId { get; set; }

        public Client? Client { get; set; }

        [Required]
        [Display(Name = "Incident No")]
        public string? IncidentNo { get; set; }
        
        [Required]
        [Display(Name = "Client No")]
        public string? ClientNo { get; set; }

当我运行应用程序时,我收到 NullReferenceException:对象引用未设置到对象的实例。在线:

@for (var i = 0; i < Model.Client.Shots.Count; i++)

两个表(客户端和镜头)都有值,所以我不确定我做错了什么?我是否遗漏了一些明显的东西?

预先感谢您提供的任何帮助。我已经盯着这个看了太久了。

c# asp.net-core entity-framework-core razor-pages nullreferenceexception
1个回答
0
投票

两个表(客户端和镜头)都有值,所以我不确定 我做错了什么?我是否遗漏了一些明显的东西?

首先,您的 Shot 表设计或模型定义违反了 3NF 数据库规范,因为通过 Client ID,您可以访问 Shot 表中的所有实体,因此,IncidentNo 和 ClientNo 只是 Client 表的重复。

但是,您的表关系不应该存在通过使用 ClientId 连接来获取数据的问题。我已经调查了您的代码片段,并尝试插入一些手动数据,它似乎按预期工作。

什么,我假设请检查您的搜索键,即您在

OnGet(int Id)
方法中传递的 Id。

除此之外,您还应该检查您的 ApplicationDbContext 定义以及是否相应地创建了您的数据库表架构。

最重要的是,请检查您的 ClientId 在 Shot 表上是否有正确的映射。

我尝试了与你相同的方法,并且我执行了迁移命令,它创建了如下数据库表:

迁移后的数据库表:

应用程序设置.json:

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\ProjectModels;Database=RazorPageTableJoinDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

Db 上下文类:

public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

        public DbSet<Client> Clients { get; set; }
        public DbSet<Shot> Shots { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            

        }
    }

Program.cs 类:

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString));

// Add services to the container.
builder.Services.AddRazorPages();

Razor Page.cs:

public class ForeignKeyTableJoinModel : PageModel
    {
        private readonly ApplicationDbContext _db;

        public Client Client { get; set; }
        public Shot Shot { get; set; }


        public ForeignKeyTableJoinModel(ApplicationDbContext db)
        {
            _db = db;
        }

        public void OnGet()
        {
            var Id = 1;
            
            Client = _db.Clients
                    .Include(client => client.Shots).FirstOrDefault(client => client.ClientId == Id);
        }
    }

输出:

注意: 确保您拥有给定 ClientId 的正确数据,并且在数据库表中它们具有正确的关系。此外,您正在 appsetting.json 连接字符串中将查询发送到正确的数据库。

© www.soinside.com 2019 - 2024. All rights reserved.