You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SqlException.Number is always 0 when using .NET framework remoting #1940
When using Remoting in .NET Framework, the SqlException.Number getter always returns 0. This makes it difficult to determine the type of SQL error that occurred. In fact, other event details are also missing, such as LineNumber, Class, and so on.
To reproduce
In a remoting client/server context, have the client call the server to insert a duplicate record that violates a unique constraint. On the server, it gets the SqlException with the Number=2627. However, when this exception is passed back to the calling client (over the remoting channel), it comes back with Number=0 (and the other error data is missing)
Expected behavior
Expected behavior is to retain the error number, and other details about the SQL error.
Further technical details
Microsoft.Data.SqlClient version: 5.1.0
.NET target: Framework 4.8, Netstandard2.0
SQL Server version: SQL Server 2019
Operating system: Windows 11
Thanks @randbrown for bringing this issue to our attention. Just to clarify, in a .NET Remoting environment, the SqlException when thrown from the server application to the client application loses the error number/data due the serialization of the SqlException's error collection. We'll have to do some investigation, but if you can provide us with a sample repro application, that would be very helpful.
Here is a repro case written as a unit test for the sake of simplicity. The issue can be demonstrated by serialize/deserialize to byte array, which shows the same problem as remoting serialization. Note the Assert() which fails. In this case I'm just pointing out the Number is 0 because that is the main thing affecting my app code, but this issue also causes the Class, LineNumber, Server, etc to be empty.
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.Data.SqlClient;usingSystem.IO;usingSystem.Runtime.Serialization.Formatters.Binary;namespaceMyApp.Common.Tests.DAL{[TestClass]publicclassSqlExceptionTests{[TestMethod]publicvoidTestSqlExceptionSerialization(){using(varconn=newSqlConnection("Data Source=(local);Initial Catalog=mydata;Integrated Security=True;User ID=;Password=;Encrypt=No")){// Try a command which produces an errorvarcommand="insert into NotATable (ID) values ('')";SqlCommandcmd=newSqlCommand(command,conn);conn.Open();try{cmd.ExecuteNonQuery();}catch(SqlExceptionexc){// Invalid object name 'NotATable'Assert.AreEqual(208,exc.Number);Assert.AreEqual(1,exc.Errors.Count);varbytes=ObjectToByteArray(exc);varexcDeserialized=(SqlException)ByteArrayToObject(bytes);// Note the deserialized does not have the Errors and thus the NumberAssert.AreEqual(0,excDeserialized.Number);Assert.AreEqual(0,excDeserialized.Errors.Count);// FAIL because excDeserialized.Number returns 0 Assert.AreEqual(exc.Number,excDeserialized.Number);// FAIL <=============}}}publicstaticbyte[]ObjectToByteArray(objectobj){BinaryFormatterbf=newBinaryFormatter();using(varms=newMemoryStream()){bf.Serialize(ms,obj);returnms.ToArray();}}publicstaticobjectByteArrayToObject(byte[]arrBytes){using(varmemStream=newMemoryStream()){varbinForm=newBinaryFormatter();memStream.Write(arrBytes,0,arrBytes.Length);memStream.Seek(0,SeekOrigin.Begin);varobj=binForm.Deserialize(memStream);returnobj;}}}}
si.AddValue("Errors",null);// Not specifying type to enable serialization of null value of non-serializable type
implying that the SqlErrorCollection is not serializable it is marked as serializable and so is SqlError, so serialization works. I can put up the PR for this single line fix for netfx only.
This should not be fixed on netcore because binary formatter is deprecated on netcore.
All required environment details provided for investigation (SqlClient 5.1.0, .NET Framework 4.8/Netstandard2.0, SQL Server 2019, Windows 11, repro steps, expected vs actual behavior)
SqlException.Number, LineNumber, Class, and other error-detail properties are backed by the Errors collection, but SqlException.GetObjectData() currently serializes Errors as null. This means any cross-AppDomain/remoting or binary-serialization round-trip (e.g. .NET Remoting, BinaryFormatter) silently loses all SQL error details, even though the info is duplicated into the Data dictionary as a workaround. This is a real correctness bug affecting error handling in legacy .NET Framework remoting scenarios; severity is moderate (P2) since it only affects niche binary-serialization/remoting use cases on .NET Framework, and a repro test case plus a proposed one-line fix (serializing Errors for netfx only, since BinaryFormatter is deprecated on .NET Core) have already been supplied by contributors.
Next Steps
Review and progress the existing linked PR Fix | Enable serialization of SqlException #4622, which appears to implement the fix described by contributors (serializing the SqlErrorCollection in GetObjectData() for the .NET Framework path only).
If PR Fix | Enable serialization of SqlException #4622 stalls, assign this issue to Copilot coding agent to implement the fix in SqlException.GetObjectData() (guarded with #if NETFRAMEWORK, since BinaryFormatter/legacy serialization is deprecated on .NET/.NET Core) and add a regression unit test mirroring the repro shared in this issue (serialize/deserialize a caught SqlException and assert Number, Errors.Count, LineNumber, Class, and Server are preserved).
Ensure any fix maintains backward compatibility and does not affect the netcore/.NET code paths, per the existing contributor guidance.
Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.
Activity
lcheunglci commentedon Mar 3, 2023
Thanks @randbrown for bringing this issue to our attention. Just to clarify, in a .NET Remoting environment, the
SqlExceptionwhen thrown from the server application to the client application loses the error number/data due the serialization of the SqlException's error collection. We'll have to do some investigation, but if you can provide us with a sample repro application, that would be very helpful.randbrown commentedon Mar 6, 2023
Here is a repro case written as a unit test for the sake of simplicity. The issue can be demonstrated by serialize/deserialize to byte array, which shows the same problem as remoting serialization. Note the Assert() which fails. In this case I'm just pointing out the Number is 0 because that is the main thing affecting my app code, but this issue also causes the Class, LineNumber, Server, etc to be empty.
Wraith2 commentedon Apr 18, 2023
I've just tried this and simply adding the error collection into the serialization at the location listed above seems to work.
Despite the comment:
SqlClient/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs
Line 56 in a6e7e0d
implying that the SqlErrorCollection is not serializable it is marked as serializable and so is SqlError, so serialization works. I can put up the PR for this single line fix for netfx only.
This should not be fixed on netcore because binary formatter is deprecated on netcore.
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\NetfxAnalysis
SqlException.Number,LineNumber,Class, and other error-detail properties are backed by theErrorscollection, butSqlException.GetObjectData()currently serializesErrorsasnull. This means any cross-AppDomain/remoting or binary-serialization round-trip (e.g. .NET Remoting,BinaryFormatter) silently loses all SQL error details, even though the info is duplicated into theDatadictionary as a workaround. This is a real correctness bug affecting error handling in legacy .NET Framework remoting scenarios; severity is moderate (P2) since it only affects niche binary-serialization/remoting use cases on .NET Framework, and a repro test case plus a proposed one-line fix (serializingErrorsfor netfx only, sinceBinaryFormatteris deprecated on .NET Core) have already been supplied by contributors.Next Steps
SqlErrorCollectioninGetObjectData()for the .NET Framework path only).SqlException.GetObjectData()(guarded with#if NETFRAMEWORK, sinceBinaryFormatter/legacy serialization is deprecated on .NET/.NET Core) and add a regression unit test mirroring the repro shared in this issue (serialize/deserialize a caughtSqlExceptionand assertNumber,Errors.Count,LineNumber,Class, andServerare preserved).