Skip to content

Bug in SQL Server provider when using UTF8 collations #2035

Description

@jtheisen

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.

I have reduced my import to a test case. See instructions to reproduce there.

Version information

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

Activity

  1. transferred this issue fromdotnet/efcoreon May 11, 2023
  2. JRahnama commented on May 11, 2023

    @JRahnama
    Contributor

    @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.

  3. jtheisen commented on May 11, 2023

    @jtheisen
    Author

    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.

  4. JRahnama commented on May 11, 2023

    @JRahnama
    Contributor

    so we do not need this var fileName = @"c:\users\jens\downloads\dewiki-20230501-pages-articles.xml.bz2";?

  5. JRahnama commented on May 11, 2023

    @JRahnama
    Contributor

    Never mind. I got it from the source.

  6. jtheisen commented on May 11, 2023

    @jtheisen
    Author

    Make sure you got the right branch.

  7. JRahnama commented on May 11, 2023

    @JRahnama
    Contributor

    @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.

  8. jtheisen commented on May 12, 2023

    @jtheisen
    Author

    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:

    1. Deleting the database from previous runs.
    2. 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
    3. cd .\testcase-for-utf8-issue
    4. Running the test: dotnet run --project Creational.Console

    I get the exception mentioned in the OP.

  9. JRahnama commented on May 12, 2023

    @JRahnama
    Contributor

    I am able to reproduce the issue. with the repro. I will get back to you on this.

  10. added
    Repro Available ✔️
    and removed on May 12, 2023
  11. 1 remaining item

  12. cheenamalhotra commented on Jul 23, 2024

    @cheenamalhotra
    Member

    @JRahnama can you provide an update on this issue - does it still occur on latest driver versions?

  13. jtheisen commented on Jul 23, 2024

    @jtheisen
    Author

    @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.

  14. jscarle commented on Nov 1, 2024

    @jscarle

    I can confirm that this bug is still current as of today.

  15. jscarle commented on Nov 9, 2024

    @jscarle

    Specifically, I can confirm this happens with data that is close to or around (can be above or below) the 8000 character mark.

  16. daiplusplus commented on Oct 22, 2025

    @daiplusplus

    FYI, @jtheisen's test-case was moved to https://github.com/jtheisen/creational-first-attempt/tree/testcase-for-utf8-issue


    Specifically, I can confirm this happens with data that is close to or around (can be above or below) the 8000 character mark.

    Methinks the problem is SqlClient incorrectly assuming String.Length is always suitable for use with SqlParameter.Size:

    Apparently, and contrary to popular belief, the n in varchar(n) is not the number-of-characters, but the number of storage bytes:

    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.&nbsp;Heft, Köthen 1811, S.&nbsp;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.
    

    Gives me this output:

    text.Length       :  2,601
    StringInfo.Length :  2,601
    UTF-8 Byte Count  :  2,634
    UTF-16 Byte Count :  5,202
    UTF-16 Byte Pairs :  2,601
    SqlParameter1.Size:  2,601 (VarChar)
    SqlParameter2.Size:  2,601 (NVarChar)
    SqlParameter3.Size:  2,634 (VarChar)
    

    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.

    BTW, please please please mark AddWithValue as [Obsolete].

    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?

  17. moved this from To triage to Backlog in SqlClient Boardon Jan 8, 2026
  18. jscarle commented on Aug 4, 2026

    @jscarle

    This is still relevant!

  19. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  20. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment 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/char SqlParameter 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.
    • Consider referencing the related BOM-prefix UTF-8 bug (SqlBulkCopy streaming ends up prefixing BOM to UTF8 source column with VARCHAR(MAX) type #3397, already fixed) since both stem from UTF-8 handling gaps in TdsParser; review for any shared code paths.

    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.

    Generated by SqlClient Issue Auto-Triage for #2035 · copilot · auto · 69.4 AIC · ⌖ 13.1 AIC · ⊞ 11.9K · ◷

  21. added a commit that references this issue on Oct 26, 2026
    671d5bd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Repro Available ✔️

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions