【问题标题】:How do I handle the SqlException "No Records Found" when using LINQ to SQL?使用 LINQ to SQL 时如何处理 SqlException“未找到记录”?
【发布时间】:2010-10-01 17:26:33
【问题描述】:

我正在使用 LINQ to SQL 在我的公司调用 sprocs。通常它工作得很好,但在某些查询中,如果没有找到它会抛出 SqlException "No Records Found"。

我应该如何处理这种情况?

这是我将拨打的示例电话:

        /// <summary>
        /// Gets the pending messages.
        /// </summary>
        /// <param name="historySearchCriteria">The history search criteria.</param>
        /// <returns><c>List</c> of pending messages.</returns>
        public List<PendingMessage> GetPendingMessages(HistorySearchCriteria historySearchCriteria)
        {
            using (MessageDataContext db = new MessageDataContext(DatabaseProperties.MessageConnectionString))
            {
                List<PendingMessage> pendingMessages = new List<PendingMessage>();

                pendingMessages.AddRange(db.usp_search_message_pending(historySearchCriteria.AccountId,
                    historySearchCriteria.TrackingNumber,
                    historySearchCriteria.StartDateTime,
                    historySearchCriteria.EndDateTime)
                    .Select(p => new PendingMessage()
                    {
                        Account = p.account,
                        ActionType = (OrderActionType) Enum.Parse(typeof(OrderActionType), p.action_type.ToString()),
                        AttemptsRemaining = p.attempts_remaining,
                        Message = p.message
                    }));

                return pendingMessages;
            }           
        }

如果没有找到记录,我只想返回一个空列表,最好的处理方法是什么。

【问题讨论】:

    标签: linq-to-sql exception sqlexception


    【解决方案1】:

    您可以简单地在处理程序中捕获该异常和return new List&lt;PendingMessage&gt;;

    【讨论】:

      【解决方案2】:

      你可以使用DefaultIfEmpty

      类似:

      pendingMessages.AddRange(
                      db.usp_search_message_pending
                         (
                             historySearchCriteria.AccountId,
                             historySearchCriteria.TrackingNumber,
                             historySearchCriteria.StartDateTime,
                             historySearchCriteria.EndDateTime
                         )
                .DefaultIfEmpty()
                .Select( /* select clause here */)
      );
      

      【讨论】:

      • 我刚刚测试了它,它仍然抛出 SqlException "No Records Found"。
      • 尝试在 AddRange 之前添加 DefaultIfEmpty 看看会发生什么。
      • 我可能是错的(经常是!)但问题的措辞让我认为存储过程引发了异常。如果是这种情况,结果将永远不会是“空的”,而是一个例外。因此,在不更改存储过程的情况下,必须像我的回答那样捕获该异常。
      【解决方案3】:

      “No Records Found”文本从何而来?

      使用导致异常的相同参数从 Management Studio 执行存储过程。

      SSMS 会报错吗?

      如果没有,请将 C# 行分成 3 个步骤:

      • 调用存储过程

      • 检查 != null 并调用 Select()

      • 检查 != null 并调用 AddRange()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多