简体   繁体   English

无法将“System.DBNull”类型的 object 转换为“System.DateTime”类型

[英]Unable to cast object of type 'System.DBNull' to type 'System.DateTime'

Hi im trying to make a notification system.嗨,我正在尝试制作一个通知系统。 Basically when i add a new row, a notification will be shown on my notificationspage realtime (i use signalR with razor pages asp.net).基本上,当我添加新行时,通知将实时显示在我的通知页面上(我使用 signalR 和 razor 页面 asp.net)。 But for some reason when i get on that page, i get these errors: Unable to cast object of type 'System.DBNull' to type 'System.DateTime'.但由于某种原因,当我进入该页面时,出现以下错误:无法将类型为“System.DBNull”的 object 转换为类型“System.DateTime”。 at myWebApp.Controllers.SpeedListener.GetAlarmList() in \myWebApp\Controllers\SpeedListener.cs:line 83 at myWebApp.Controllers.SpeedListener.ListenForAlarmNotifications() in \myWebApp\Controllers\SpeedListener.cs:line 43在 myWebApp.Controllers.SpeedListener.GetAlarmList() 在 \myWebApp\Controllers\SpeedListener.cs:line 83 在 myWebApp.Controllers.SpeedListener.ListenForAlarmNotifications() 在 \myWebApp\Controllers\SpeedListener.cs:line 43

So apparently theres a problem at the controller.因此,controller 显然存在问题。 Here is the code of the controller这是 controller 的代码

namespace myWebApp.Controllers
{
    public class SpeedListener :Controller
    {
        private IHubContext<speedalarmhub> _hubContext;
        private IMemoryCache _cache;
        public SpeedListener(IHubContext<speedalarmhub> hubContext,IMemoryCache cache)
        {
            _hubContext = hubContext;
            _cache = cache; 
        }
        public static string  cs = Database.Database.Connector();
        public void ListenForAlarmNotifications()
        {
            NpgsqlConnection conn = new NpgsqlConnection(cs);
            conn.StateChange += conn_StateChange;
            conn.Open();
            var listenCommand = conn.CreateCommand();
            listenCommand.CommandText = $"listen notifytickets;";
            listenCommand.ExecuteNonQuery();
            conn.Notification += PostgresNotificationReceived;
            _hubContext.Clients.All.SendAsync(this.GetAlarmList());
            while (true)
            {
                conn.Wait();
            }
        }
        private void PostgresNotificationReceived(object sender, NpgsqlNotificationEventArgs e)
        {

            string actionName = e.Payload.ToString();
            string actionType = "";
            if (actionName.Contains("DELETE"))
            {
                actionType = "Delete";
            }
            if (actionName.Contains("UPDATE"))
            {
                actionType = "Update";
            }
            if (actionName.Contains("INSERT"))
            {
                actionType = "Insert";
            }
            _hubContext.Clients.All.SendAsync("ReceiveMessage", this.GetAlarmList());
        }
        public string GetAlarmList()
        {
            List<NotificationModel> not = new List<NotificationModel>();
            using var con = new NpgsqlConnection(cs);
            {
                string query = "Select datumnu, bericht FROM notification";
                using NpgsqlCommand cmd = new NpgsqlCommand(query, con);
                {
                    cmd.Connection = con;
                    con.Open();
                    using (NpgsqlDataReader dr = cmd.ExecuteReader())
                    {
                        
                        while (dr.Read())
                        {
                            not.Add(new NotificationModel { Datenow = ((DateTime) dr["datumnu"]).ToString("yyyy/MM/dd"), Bericht = dr["bericht"].ToString() });
                        }
                    }
                    
                    con.Close();
                }
            }
            _cache.Set("notification", SerializeObjectToJson(not));
            return _cache.Get("notification").ToString();
        }
        public String SerializeObjectToJson(Object notification)
        {
            try
            {
                
                return  Newtonsoft.Json.JsonConvert.SerializeObject(notification);
            }
            catch (Exception) { return null; }
        }
        private void conn_StateChange(object sender, System.Data.StateChangeEventArgs e)
        {

            _hubContext.Clients.All.SendAsync("Current State: " + e.CurrentState.ToString() + " Original State: " + e.OriginalState.ToString(), "connection state changed");
        }
    }
}

If needed here is my hub如果需要,这里是我的中心

namespace myWebApp.Hubs
{
     
    public class speedalarmhub : Hub
    {
        private IMemoryCache _cache;
        private IHubContext<speedalarmhub> _hubContext;
         public speedalarmhub(IMemoryCache cache, IHubContext<speedalarmhub> hubContext)
        {
            _cache = cache;
            _hubContext = hubContext; 
        }

        public async Task SendMessage()
        {
            if (!_cache.TryGetValue("notification", out string response))
            {
                SpeedListener speedlist = new SpeedListener(_hubContext,_cache);
                speedlist.ListenForAlarmNotifications();
                string jsonspeedalarm = speedlist.GetAlarmList();
                _cache.Set("notification", jsonspeedalarm);
                await Clients.All.SendAsync("ReceiveMessage", _cache.Get("notification").ToString());
            }
            else
            {
                await Clients.All.SendAsync("ReceiveMessage", _cache.Get("notification").ToString());
            }
        }

    }
}

the table name in postgresql is called 'notification', i have two column called 'bericht' with type varchar and 'datumnu' with type date. postgresql 中的表名称为“通知”,我有两列名为“bericht”,类型为 varchar,“datumnu”,类型为日期。

Edit suggested by mjwills DateTime don't accept null value. mjwills DateTime 建议的编辑不接受 null 值。 Check if the value is null and assigne a default value检查该值是否为 null 并分配一个默认值

while (dr.Read())
{
    not.Add(new NotificationModel { Datenow = ((DateTime) dr["datumnu"]).ToString("yyyy/MM/dd"), Bericht = dr["bericht"].ToString() });
}

Become变得

while (dr.Read())
{
    DateTime defaultDateTime = DateTime.Now;
    if(dr.IsNull("datumnu")){
        defaultDateTime = (DateTime)dr["datumnu"];
    }

    not.Add(new NotificationModel { Datenow = defaultDateTime, Bericht = dr["bericht"].ToString() });
}

in single line在单行

while (dr.Read())
{
    not.Add(new NotificationModel { Datenow = (dr.IsNull("datumnu") ? DateTime.Now : (DateTime)dr["datumnu"]), Bericht = dr["bericht"].ToString() });
}

暂无
暂无

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

相关问题 Object 类型 'System.DBNull' 无法转换为类型 'System.DateTime' - Object of type 'System.DBNull' cannot be converted to type 'System.DateTime' System.InvalidCastException:无法将类型为System.DBNull的对象转换为类型为System.String的对象 - System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String' 转换:无法将“System.DBNull”类型的对象转换为“System.String”类型 - Transformation: Unable to cast object of type 'System.DBNull' to type 'System.String' RowDataBound:从dataTable获取值! 无法将“System.DBNull”类型的对象强制转换为“System.String”类型 - RowDataBound : Getting value from dataTable ! Unable to cast object of type 'System.DBNull' to type 'System.String' SqlSessionState:无法将类型为System.DBNull的对象强制转换为类型为System.Byte [] - SqlSessionState: Unable to cast object of type System.DBNull to type System.Byte[] 无法将“System.DBNull”类型的对象转换为 Scaffold-DbContext .Net Core 中的“System.String”类型 - Unable to cast object of type 'System.DBNull' to type 'System.String' in Scaffold-DbContext .Net Core Entity Framework Group BY 导致无法将“System.DBNull”类型的对象转换为“System.String”类型 - Entity Framework Group BY causing Unable to cast object of type 'System.DBNull' to type 'System.String' 获取所有产品时无法将类型为“System.DBNull”的 object 转换为类型“System.String” - Unable to cast object of type 'System.DBNull' to type 'System.String' On getting all Products 无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。 错误 - Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. error 如何修复无法将类型为“ System.DBNull”的对象转换为类型为“ System.String”的对象 - How can i fix Unable to cast object of type 'System.DBNull' to type 'System.String`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM