You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core读取SQL Server含NULL日期列时中断,需将NULL替换为空格的技术求助

ASP.NET Core读取SQL Server含NULL日期列时中断,需将NULL替换为空格的技术求助

嘿,我来帮你搞定这个问题!你遇到的读取中断问题,根源在于直接用reader.GetString(3)读取可能为NULL的日期列——当数据库里这个字段是NULL时,GetString方法会直接抛出异常,打断你的读取循环。而且你代码里把if语句直接写在对象初始化器里,这本身也是语法错误哦。

下面是修正后的完整代码,我标注了关键修改点:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Data.SqlClient;

namespace Rectusoft_Tournament_organizer.Pages
{
    public class TeamsModel : PageModel
    {
        public List<TeamInfo1> listTeams = new();
        public string? sessionvariable;

        public void OnGet()
        {
            try
            {
                String connectionString = "D********************";
                using SqlConnection connection = new(connectionString);
                connection.Open();

                String sql = "select team.naam as teamnaam, land.naam as landnaam, land.vlag, dbo.fnBetalingsdatum(team.id) as datum, division.naam , multiplificator_divisie from team, land, division where team.id_land = land.id and team.id_division = division.Id and team.id_toernooi = '86188502-2c57-4931-addc-9813959bbd97' and team.aktief = 'J' order by multiplificator_divisie desc, CASE WHEN dbo.fnBetalingsdatum(team.id) IS NULL THEN 1 ELSE 0 END, dbo.fnBetalingsdatum(team.id), id_division";

                using SqlCommand command = new(sql, connection);
                using SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    TeamInfo1 teamInfo1 = new()
                    {
                        naam = reader.GetString(0),
                        land = reader.GetString(1),
                        vlag = reader.GetString(2),
                        // 关键修改:先安全判断是否为数据库NULL,再赋值
                        betaling = reader.IsDBNull(3) 
                            ? " "  // 这里替换成你需要的空格,想保留---就换成"---"
                            : reader.GetDateTime(3).ToString("dd-MMM-yyyy")
                    };

                    listTeams.Add(teamInfo1);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("NOT Connected");
                Console.WriteLine("Exception: connectie NIET ok " + ex.Message);
            }
        }
    }

    public class TeamInfo1
    {
        public String? naam;
        public String? land;
        public String? vlag;
        public String? betaling;
    }
}

给你拆解下核心修复逻辑:

  • 用reader.IsDBNull(3)判断第4列(索引从0开始)是否为数据库NULL,这个方法不会抛出异常,是安全的判断方式,避免了原代码先读值再判断的错误逻辑。
  • 用三元运算符简化赋值,符合C#对象初始化器的语法规则,解决了原代码里的语法错误。
  • 当字段为NULL时直接赋值空格" ",如果还是想用"---"作为占位符,直接替换掉" "就行。

这样修改后,你的读取循环就不会被NULL字段打断,还能把空日期替换成你需要的内容啦!

备注:内容来源于stack exchange,提问作者New' asp.net core' One

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 16:04:38