Repository navigation
Closed
Description
Bug description
When a constant of type xml (SQL Server) is used in a query, the prefix N is not being inserted before the single quotes, so the string is considered as non-Unicode, and therefore the database collation's codepage is applied. This causes a loss of data.
Although WHERE is not allowed on an xml column, such constants can still appear in UPDATE SET clauses, or in the SELECT.
Your code
The simplest repro is just a SELECT with an emoji in an XML string. In this case you can verify the string does have the correct SqlServerStringTypeMapping with the xml type, but the N prefix is not being generated.
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class Program
{
public static void Main()
{
using var db = new MyDb();
Console.WriteLine(
db.MyEntities
.Select(e => e.SomeXml ?? "<x Attr=\"😭\" />")
.ToQueryString());
}
}
public class MyDb : DbContext
{
public DbSet<MyEntity> MyEntities {get;set;} = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().Property(p => p.SomeXml).HasColumnType("xml");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source = .");
}
}
public class MyEntity
{
public int Id {get;set;}
public string? SomeXml {get;set;}
}You can see the results are incorrect by looking at this db<>fiddle
SELECT COALESCE([m].[SomeXml], '<x Attr="😭" />')
FROM [MyEntities] AS [m]outputs
<?xml version="1.0" encoding="utf-16"?>
<x Attr="??" />instead of
<?xml version="1.0" encoding="utf-16"?>
<x Attr="😭" />EF Core version
10.0.9
Database provider
Microsoft.EntityFrameworkCore.SqlServer
Target framework
.NET 10
Operating system
No response
IDE
No response
Reacted by Copilot
Activity
Charlieface commentedon Jun 14, 2026
It seems to me the bug is very simple: in
SqlServerStringTypeMappingtheGenerateNonNullSqlLiteralfunction relies on_isUtf16as to whether the to output theNprefix. Which is set in the constructor by this line:efcore/src/EFCore.SqlServer/Storage/Internal/SqlServerStringTypeMapping.cs
Line 113 in 5538cb2
So it's looking for the parameters to be
IsUnicodeand for theStoreTypeto begin with an/N, which excludesxml.Exactly why this variable even exists is unclear to me. I see no reason why we couldn't just rely on
base.IsUnicode. Be that as it may, if you really wanted a separate variable it should have just been:Add triage analysis for issue #38429 (xml literals missing N prefix)
AndriySvyryd commentedon Jun 18, 2026
The only issue with flipping to Unicode is that SQL Server rejects an
nvarcharliteral that contains an explicit XML prolog encoding declaration when it is converted toxml, because the declared encoding (e.g.utf-8) conflicts with the UTF-16nvarcharstring. The non-Unicode form is accepted. Verified on SQL Server 2025:So flipping
xmlto emitNliterals would break queries that embed anxmlstring constant whose content begins with<?xml ... encoding="..."?>(a non-UTF‑16 encoding). Such prologs are common when an application round-trips XML that was originally produced elsewhere.This would have to be documented as a breaking change
Charlieface commentedon Jun 18, 2026
That's true, although by the same token an embedded prolog
encoding="utf-16"doesn't work at the moment because of the incorrect encoding.Options as I see it:
GenerateNonNullSqlLiteraland conditionally output theN.xmlcolumns to use theUnicodeattribute.utf-16. Transmitting XML as UTF-16 and marking it with autf-8prolog is itself a bug (ie by the user) so not as ridiculous as it sounds. SQL Server does this itself if you convert non-Unicodevarchartoxml.The confounding issue here is that SqlClient deals with parameters of
SqlDbType.Xmlvery strangely. It only passes the parameter typed asxmlif you give it aSqlXmlvalue, for which you'd need to pass either aStreamor anXmlReader. For barestringit passes it asnvarchar(max), which already fails with autf-8prolog, but not withutf-16.Perhaps we should always be passing in
SqlXmlas the parameter? Might need some work around getting an efficient customStreamover astringwithout any copying.Send SQL Server xml parameters as SqlXml (fix #38429)
Charlieface commentedon Jun 18, 2026
Having said that, by the looks of the code in
SqlParameter.CoercedValueit's just reading theStreamback into astring. So that's going to be inefficient. We might as well stick tostringanyway, but passing it inside aSqlXmlto get the correct type server-side.Either way,
xmlcolumns are currently broken in both directions at the moment, if you have a prolog. Literals only work with utf-8 and parameters only work with utf-16.Charlieface commentedon Jun 19, 2026
A bit of testing seems to show that we can simply do
AndriySvyryd commentedon Jun 19, 2026
What did you observe if you only set it before?
Charlieface commentedon Jun 19, 2026
That although the
SqlDbTypewas set correctly, the param was still sent asnvarchar. This is probably a bug (or a "feature") in SqlClient to be honest.I think your current code is correct, it sets it afterwards, but you might want to add a test to validate this.
Charlieface commentedon Jun 19, 2026
@AndriySvyryd
Thanks for the quick work.
Wondering why you are using an
XmlReaderrather than more efficiently just passing in the string value as I mentioned. As SqlClient will just read the whole reader back into a string.If you all you want is to validate the XML using a reader, you could just loop the reader to ensure it doesn't fail, then send the original string.
AndriySvyryd commentedon Jun 19, 2026
I was trying to avoid adding more parsing logic, but as you say, using
XmlReaderis inefficient.Send SQL Server xml parameters as SqlXml (dotnet#38462)
Charlieface commentedon Jun 28, 2026
@AndriySvyryd
Just in case you were wondering quite how inefficient it is, I made some benchmarks. Just passing in the value as a
SqlParameterand doingSELECT DATALENGTH(@p). I used a 64kb value of something like<root><a>aaaaaa</a><a>aaaaaaa<a/><a>........ etc</root>.I also tested using a custom
Streamwhich reads the string direct from memory as UTF-16.You can see that using an
XmlReaderis quite a bit slower and much more memory hungry than using the raw string or aStringReader. That itself is unsurprising given how complex it is, butSqlXmlover any of those is far worse. A reading of the code makes it clear:SqlXmlaccepts either aStreamorXmlReader:Stream: creates anXmlReaderover it.XmlReader: Rather than just using it like you'd expect, it writes it to aMemoryStreamand uses that to create a newXmlReader.SqlParameter.CoerceValue:XmlReader: will stream it over the wire directly.SqlXml: will write it back to a string.So if you use
SqlXmlwith aXmlReaderthen you end up creating the whole XML again twice: once inSqlXmland once inSqlParameter. Problem is the former is in dotnet/runtime repo and the latter is in dotnet/sqlclient so it's two different teams. We could raise an issue in both but I see a much simpler solution from the above: just use theXmlReaderdirectly.AndriySvyryd commentedon Jun 29, 2026
@Charlieface Thanks for the detailed analysis: #38506
Using a naked XmlReader messed up our tests because the stream cannot be rewound. So I went back to parsing, with a more flexible approach.