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
Bug in SQL Server provider when using UTF8 collations #2035
I've encountered exceptions when using EF with SQL Server and configuring
the database and all column collations to be a UTF8 collation and
all columns to use varchar rather than nvarchar (as one should with UTF8 collations on SQL Server, somewhat counter-intuitively).
I've been doing this for a while now without obvious issues, but in a project that does some massive import of larger text portions some of the inserts fail with an exception:
SqlException: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 7 ("@p8"): Data type 0xA7 has an invalid data length or metadata length.
This does not happen with the traditional nvarchar type, and it happens only in some (thankfully reproducible) circumstances.
SQL Server version: Microsoft SQL Server Developer (64-bit) 16.0.1050.5 on Windows
EF Core version: 6.0.16
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
Operating system: Windows 11
IDE: Visual Studio 2022 17.5.2
If you mean the database itself, it's created by the console app on startup. It just needs to be allowed to, which it should be when you have a local SQL Server instance and your user has admin rights there.
@jtheisen I keep getting Invalid object name 'Pages'. I cannot, did not have time to, debug the code at the moment. Is it possible to fix that and update the repro.
You get that error when the schema hasn't been created yet, but that should have been done in Program.cs in the db.Database.Migrate(); call - or at least it should fail there if it can't do that.
I've just repeated using the testcase, this time using the command line tools by doing:
Deleting the database from previous runs.
Making a fresh checkout: git clone --single-branch --branch testcase-for-utf8-issue https://github.com/jtheisen/creational.git testcase-for-utf8-issue-for-utf8-issue
cd .\testcase-for-utf8-issue
Running the test: dotnet run --project Creational.Console
It's a common perception, in char and varchar or in nchar and nvarchar, that n defines the number of characters. This is because, in the example of a char(10) column, 10 ASCII characters in the range 0 - 127 can be stored by using a collation such as Latin1_General_100_CI_AI, because each character in this range uses only 1 byte.
However, in char and varchar, n defines the string size in bytes (0 - 8,000), and in nchar and nvarchar, n defines the string size in byte-pairs (0 - 4,000).
n never defines numbers of characters that can be stored.
Somewhat amusingly, the SqlClient source-code goes against the documentation and has a method named _IsSizeInCharacters, despite the documentation's protestations that "n` never defines numbers of characters that can be stored". Welp!
I think I've made a minimal demonstration (tested using C# 12 on .NET 8 or 9) in LinqPad or a console project:
using System.Globalization;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
String text = JsonConvert.DeserializeObject<String>(
@"""<!-- Für Informationen zum Umgang mit dieser Vorlage siehe bitte [[Wikipedia:Taxoboxen]]. -->\n{{Taxobox\n| Taxon_Name = Rohrsänger\n| Taxon_WissName = Acrocephalus\n| Taxon_Rang = Gattung\n| Taxon_Autor = [[Johann Andreas Naumann|J. A. Naumann]] & [[Johann Friedrich Naumann|J. F. Naumann]], 1811\n| Taxon2_Name = Rohrsängerartige\n| Taxon2_WissName = Acrocephalidae\n| Taxon2_Rang = Familie\n| Taxon3_WissName = Locustelloidea\n| Taxon3_Rang = Überfamilie\n| Taxon4_Name = Singvögel\n| Taxon4_WissName = Passeri\n| Taxon4_Rang = Unterordnung\n| Taxon5_Name = Sperlingsvögel\n| Taxon5_WissName = Passeriformes\n| Taxon5_Rang = Ordnung\n| Taxon6_Name = Neukiefervögel\n| Taxon6_WissName = Neognathae\n| Taxon6_Rang = Unterklasse\n| Bild = Carricero tordal.jpg\n| Bildbeschreibung = [[Drosselrohrsänger]] (''Acrocephalus arundinaceus'')\n}}\n[[Datei:Marshwarbler primaryprojection.jpg|mini|Sumpfrohrsänger (''A. palustris''), einer der oberseits einfarbigen Rohrsänger.]]\n[[Datei:Acrocephalus scirpaceus 01 by-dpc.jpg|mini|Nest mit Einern des [[Teichrohrsänger]]s (''Acrocephalus scirpaceus'')]]\n[[Datei:Acrocephalus palustris 03.JPG|mini|Nest und Jungvögel des [[Sumpfrohrsänger]]s (''Acrocephalus palustris'')]]\nDie '''Rohrsänger''' (''Acrocephalus'') sind eine [[Gattung (Biologie)|Gattung]] der [[Vögel]].<ref>Johann Andreas Naumann, Friedrich Naumann: ''Naturgeschichte der Land- und Wasser-Vögel des nördlichen Deutschlands und angränzender Länder. Nachtrag.'' 4. Heft, Köthen 1811, S. 199</ref> Aktuell wird die Gattung zusammen mit anderen Gattungen in eine eigene [[Familie (Biologie)|Familie]] [[Rohrsängerartige|Acrocephalidae]] gestellt<ref name=\""IOC\""> Frank Gill, David Donsker: [https://www.worldbirdnames.org/bow/bushtits/ ''Bushtits, leaf warblers & reed warblers.''] IOC World Bird Names, 2020 (version 10.2.)</ref>, traditionell wurde sie der Familie der [[Grasmückenartige]]n (Sylviidae) zugeordnet. Die Rohrsänger sind in der [[Alte Welt|Alten Welt]] verbreitet, den größten Artenreichtum weist die [[Paläarktis]] auf. Zurzeit werden 43 Arten anerkannt.<ref name=\""IOC\""/>\n\n== Beschreibung ==\nRohrsänger sind schlanke Singvögel mit schmalem bis abgeflachtem Schnabel, der an der Basis wenige kräftige Borsten aufweist. Der Schwanz ist meist gestuft bis stark gerundet und auf dem [[Vogelfuß|Tarsometatarsus]] bleibt die Beschilderung auch bei [[adult]]en Vögeln sichtbar.\n\nDie Gattung lässt sich in zwei generelle Färbungstypen unterteilen. Bei der einen Gruppe ist die Oberseite weitgehend einfarbig braun oder oliv"""
)!;
//
StringInfo strInfo = new StringInfo( text );
Int32 utf8Bytes = Encoding.UTF8.GetByteCount( text );
Int32 utf16Bytes = Encoding.Unicode.GetByteCount( text );
Console.WriteLine( "text.Length : {0,6:N0}", text.Length );
Console.WriteLine( "StringInfo.Length : {0,6:N0}", strInfo.LengthInTextElements );
Console.WriteLine( "UTF-8 Byte Count : {0,6:N0}", utf8Bytes );
Console.WriteLine( "UTF-16 Byte Count : {0,6:N0}", utf16Bytes );
Console.WriteLine( "UTF-16 Byte Pairs : {0,6:N0}", utf16Bytes / 2 );
SqlParameter p1 = new SqlParameter( "@utf8Value", SqlDbType.VarChar ) { Value = text };
SqlParameter p2 = new SqlParameter( "@utf8Value", value: text ); // <-- This is the ctor that the infamous `AddWithValue` method uses. It infers `SqlDbType: NVarChar`.
SqlParameter p3 = new SqlParameter( "@utf8Value", SqlDbType.VarChar, size: 2634 ) { Value = text };
Console.WriteLine( "SqlParameter1.Size: {0,6:N0} ({1})", p1.Size, p1.SqlDbType );
Console.WriteLine( "SqlParameter2.Size: {0,6:N0} ({1})", p2.Size, p2.SqlDbType );
Console.WriteLine( "SqlParameter3.Size: {0,6:N0} ({1})", p3.Size, p3.SqlDbType );
Debug.Assert( p1.Size == 2601 ); // <-- When using UTF8 Collations then I believe that SqlClient's 6.1.2 default internal calculation of `p.Size == 2601` is incorrect - it should be `p.Size == 2634`
Debug.Assert( p2.Size == 2601 ); // <-- Ditto.
Debug.Assert( p3.Size == 2634 ); // <-- I feel this is what it should be.
Notice that UTF-8 storage of that string takes 2,634 bytes - not the assumed 2,601 bytes. Which means the UTF-8 string bytes will be truncated when sent to SQL Server, which explains the "Data type 0xA7 has an invalid data length or metadata length." error.
For applications facing this issue, methinks a quick-fix is to specify an explicit SqlParameter.Size using Encoding.UTF8.GetByteCount when you know you're using UTF-8 collation in storage.
Assuming that misuse of text.Length is the problem, I am very surprised that the root-cause of this issue went unnoticed in the 6 years since SQL Server 2019's UTF-8 support was added. Though I assume everyone is still using SqlDbType.NVarChar in SqlParameter out-of-habit, I guess?
All required environment details provided for investigation
Area
Area\Engineering
Duplicates
None found (searched for UTF8 collation / SqlParameter Size / varchar truncation issues; related but distinct: #1208 "UTF8 Support via GetBytes or GetFieldValue", #3397 "SqlBulkCopy streaming ends up prefixing BOM to UTF8 source column")
Regression
Not indicated — long-standing issue since UTF-8 collation support was added in SQL Server 2019; still reproduces on Microsoft.Data.SqlClient 5.2.1 and later
Analysis
This is a confirmed bug in how SqlParameter/TdsParser compute the size (in bytes) of varchar/char parameters when the underlying column collation is UTF-8. SqlClient currently derives the parameter's byte length from String.Length (character count), but for UTF-8 collations a character can occupy more than 1 byte, so multi-byte characters cause the computed size to be smaller than the actual UTF-8 byte count. This leads to truncated data being sent to the server and surfaces as "Data type 0xA7 has an invalid data length or metadata length" RPC errors once data nears/crosses size boundaries (e.g. ~8000-byte VARCHAR limit or MAX-type internal calculations). A detailed root-cause analysis and reproduction (including exact byte-count math and a minimal failing example) was provided by @daiplusplus in the thread. Severity: P2 — affects any application using UTF-8 collations with non-ASCII varchar data and SqlParameter/AddWithValue, a growing scenario as UTF-8 collations gain adoption.
Next Steps
Assign this issue to Copilot coding agent to investigate the parameter size/length calculation logic for varchar/charSqlParameter values (likely in TdsParser.cs and the size-inference path used by SqlParameter/AddWithValue, including any _IsSizeInCharacters-related logic) and correct it to use Encoding.UTF8.GetByteCount (or the appropriate collation-aware byte length) instead of String.Length when the target column/parameter uses a UTF-8 collation, mirroring how nvarchar byte-pair sizing is already handled correctly.
Add unit/functional tests covering SqlParameter.Size inference for VarChar/Char parameters against UTF-8 collated columns with strings containing multi-byte UTF-8 characters, including sizes at/near the 8000-byte VARCHAR boundary.
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
JRahnama commentedon May 11, 2023
@jtheisen thanks for opening the issue and special thanks for such a detailed repro. Seems like a file is missing in the repro at this section.
jtheisen commentedon May 11, 2023
If you mean the database itself, it's created by the console app on startup. It just needs to be allowed to, which it should be when you have a local SQL Server instance and your user has admin rights there.
JRahnama commentedon May 11, 2023
so we do not need this
var fileName = @"c:\users\jens\downloads\dewiki-20230501-pages-articles.xml.bz2";?JRahnama commentedon May 11, 2023
Never mind. I got it from the source.
jtheisen commentedon May 11, 2023
Make sure you got the right branch.
JRahnama commentedon May 11, 2023
@jtheisen I keep getting
Invalid object name 'Pages'.I cannot, did not have time to, debug the code at the moment. Is it possible to fix that and update the repro.jtheisen commentedon May 12, 2023
You get that error when the schema hasn't been created yet, but that should have been done in
Program.csin thedb.Database.Migrate();call - or at least it should fail there if it can't do that.I've just repeated using the testcase, this time using the command line tools by doing:
git clone --single-branch --branch testcase-for-utf8-issue https://github.com/jtheisen/creational.git testcase-for-utf8-issue-for-utf8-issuecd .\testcase-for-utf8-issuedotnet run --project Creational.ConsoleI get the exception mentioned in the OP.
JRahnama commentedon May 12, 2023
I am able to reproduce the issue. with the repro. I will get back to you on this.
1 remaining item
cheenamalhotra commentedon Jul 23, 2024
@JRahnama can you provide an update on this issue - does it still occur on latest driver versions?
jtheisen commentedon Jul 23, 2024
@cheenamalhotra I just tested EF Core 8.07 with Microsoft.Data.SqlClient 5.2.1, same thing.
Updated the branch in the test case repo.
jscarle commentedon Nov 1, 2024
I can confirm that this bug is still current as of today.
jscarle commentedon Nov 9, 2024
Specifically, I can confirm this happens with data that is close to or around (can be above or below) the 8000 character mark.
daiplusplus commentedon Oct 22, 2025
FYI, @jtheisen's test-case was moved to https://github.com/jtheisen/creational-first-attempt/tree/testcase-for-utf8-issue
Methinks the problem is
SqlClientincorrectly assumingString.Lengthis always suitable for use withSqlParameter.Size:Apparently, and contrary to popular belief, the
ninvarchar(n)is not the number-of-characters, but the number of storage bytes:Somewhat amusingly, the
SqlClientsource-code goes against the documentation and has a method named_IsSizeInCharacters, despite the documentation's protestations that "n` never defines numbers of characters that can be stored". Welp!I think I've made a minimal demonstration (tested using C# 12 on .NET 8 or 9) in LinqPad or a console project:
Gives me this output:
Notice that UTF-8 storage of that string takes 2,634 bytes - not the assumed 2,601 bytes. Which means the UTF-8 string bytes will be truncated when sent to SQL Server, which explains the "Data type 0xA7 has an invalid data length or metadata length." error.
For applications facing this issue, methinks a quick-fix is to specify an explicit
SqlParameter.SizeusingEncoding.UTF8.GetByteCountwhen you know you're using UTF-8 collation in storage.BTW, please please please mark
AddWithValueas[Obsolete].Assuming that misuse of
text.Lengthis the problem, I am very surprised that the root-cause of this issue went unnoticed in the 6 years since SQL Server 2019's UTF-8 support was added. Though I assume everyone is still usingSqlDbType.NVarCharinSqlParameterout-of-habit, I guess?jscarle commentedon Aug 4, 2026
This is still relevant!
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\EngineeringAnalysis
This is a confirmed bug in how
SqlParameter/TdsParsercompute the size (in bytes) ofvarchar/charparameters when the underlying column collation is UTF-8. SqlClient currently derives the parameter's byte length fromString.Length(character count), but for UTF-8 collations a character can occupy more than 1 byte, so multi-byte characters cause the computed size to be smaller than the actual UTF-8 byte count. This leads to truncated data being sent to the server and surfaces as"Data type 0xA7 has an invalid data length or metadata length"RPC errors once data nears/crosses size boundaries (e.g. ~8000-byte VARCHAR limit or MAX-type internal calculations). A detailed root-cause analysis and reproduction (including exact byte-count math and a minimal failing example) was provided by@daiplusplusin the thread. Severity: P2 — affects any application using UTF-8 collations with non-ASCIIvarchardata andSqlParameter/AddWithValue, a growing scenario as UTF-8 collations gain adoption.Next Steps
varchar/charSqlParametervalues (likely inTdsParser.csand the size-inference path used bySqlParameter/AddWithValue, including any_IsSizeInCharacters-related logic) and correct it to useEncoding.UTF8.GetByteCount(or the appropriate collation-aware byte length) instead ofString.Lengthwhen the target column/parameter uses a UTF-8 collation, mirroring hownvarcharbyte-pair sizing is already handled correctly.SqlParameter.Sizeinference forVarChar/Charparameters against UTF-8 collated columns with strings containing multi-byte UTF-8 characters, including sizes at/near the 8000-byte VARCHAR boundary.TdsParser; review for any shared code paths.Fix multibyte ANSI parameter sizing across RPC and encrypted metadata