Skip to content

xml constants do not have the N prefix #38429

Closed

Description

@Charlieface

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;}
}

dotnetfiddle

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

Activity

  1. Charlieface commented on Jun 14, 2026

    @Charlieface
    Author

    It seems to me the bug is very simple: in SqlServerStringTypeMapping the GenerateNonNullSqlLiteral function relies on _isUtf16 as to whether the to output the N prefix. Which is set in the constructor by this line:

    _isUtf16 = parameters.Unicode && parameters.StoreType.StartsWith("n", StringComparison.OrdinalIgnoreCase);

    So it's looking for the parameters to be IsUnicode and for the StoreType to begin with a n/N, which excludes xml.

    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:

    _isUtf16 = parameters.Unicode;
  2. added a commit that references this issue on Jun 18, 2026
  3. added this to the 11.0.0 milestone on Jun 18, 2026
  4. AndriySvyryd commented on Jun 18, 2026

    @AndriySvyryd
    Member

    The only issue with flipping to Unicode is that SQL Server rejects an nvarchar literal that contains an explicit XML prolog encoding declaration when it is converted to xml, because the declared encoding (e.g. utf-8) conflicts with the UTF-16 nvarchar string. The non-Unicode form is accepted. Verified on SQL Server 2025:
     

    -- current (no N): OK
    DECLARE @x xml = '<?xml version="1.0" encoding="utf-8"?><r>a</r>';   -- succeeds
     
    -- proposed (with N): fails
    DECLARE @y xml = N'<?xml version="1.0" encoding="utf-8"?><r>a</r>';
    -- Msg 9402: XML parsing: line 1, character 38, unable to switch the encoding

     
    So flipping xml to emit N literals would break queries that embed an xml string 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

  5. Charlieface commented on Jun 18, 2026

    @Charlieface
    Author

    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:

    • Detect the prolog in GenerateNonNullSqlLiteral and conditionally output the N.
    • Allow xml columns to use the Unicode attribute.
    • Switch the prolog to utf-16. Transmitting XML as UTF-16 and marking it with a utf-8 prolog is itself a bug (ie by the user) so not as ridiculous as it sounds. SQL Server does this itself if you convert non-Unicode varchar to xml.

    The confounding issue here is that SqlClient deals with parameters of SqlDbType.Xml very strangely. It only passes the parameter typed as xml if you give it a SqlXml value, for which you'd need to pass either a Stream or an XmlReader. For bare string it passes it as nvarchar(max), which already fails with a utf-8 prolog, but not with utf-16.

    Perhaps we should always be passing in SqlXml as the parameter? Might need some work around getting an efficient custom Stream over a string without any copying.

  6. added a commit that references this issue on Jun 18, 2026
    a17073c
  7. Charlieface commented on Jun 18, 2026

    @Charlieface
    Author

    Having said that, by the looks of the code in SqlParameter.CoercedValue it's just reading the Stream back into a string. So that's going to be inefficient. We might as well stick to string anyway, but passing it inside a SqlXml to get the correct type server-side.

    Either way, xml columns 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.

  8. Charlieface commented on Jun 19, 2026

    @Charlieface
    Author

    A bit of testing seems to show that we can simply do

    sqlParameter.Value = value;   // the string
    sqlParameter.SqlDbType = SqlDbType.Xml;   // you MUST set it again after setting the value
  9. AndriySvyryd commented on Jun 19, 2026

    @AndriySvyryd
    Member

    sqlParameter.SqlDbType = SqlDbType.Xml; // you MUST set it again after setting the value

    What did you observe if you only set it before?

  10. Charlieface commented on Jun 19, 2026

    @Charlieface
    Author

    sqlParameter.SqlDbType = SqlDbType.Xml; // you MUST set it again after setting the value

    What did you observe if you only set it before?

    That although the SqlDbType was set correctly, the param was still sent as nvarchar. 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.

  11. Charlieface commented on Jun 19, 2026

    @Charlieface
    Author

    @AndriySvyryd

    Thanks for the quick work.

    Wondering why you are using an XmlReader rather 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.

  12. AndriySvyryd commented on Jun 19, 2026

    @AndriySvyryd
    Member

    Wondering why you are using an XmlReader rather than more efficiently just passing in the string value as I mentioned. As SqlClient will just read the whole reader back into a string.

    I was trying to avoid adding more parsing logic, but as you say, using XmlReader is inefficient.

  13. added a commit that references this issue on Jun 23, 2026
    3501892
  14. Charlieface commented on Jun 28, 2026

    @Charlieface
    Author

    @AndriySvyryd

    I was trying to avoid adding more parsing logic, but as you say, using XmlReader is inefficient.

    Just in case you were wondering quite how inefficient it is, I made some benchmarks. Just passing in the value as a SqlParameter and doing SELECT 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 Stream which reads the string direct from memory as UTF-16.

    Method Mean Error StdDev Gen0 Gen1 Allocated
    SqlXmlWithStringReader 215.6 μs 2.83 μs 2.51 μs 10.9863 1.4648 169.2 KB
    SqlXmlWithXmlReaderStream 216.2 μs 2.29 μs 2.03 μs 11.2305 1.4648 173.28 KB
    SqlXmlWithStream 221.6 μs 5.57 μs 8.17 μs 11.2305 1.4648 173.28 KB
    XmlReaderStringReader 157.5 μs 2.23 μs 1.86 μs 1.9531 - 32.41 KB
    XmlReaderStream 158.5 μs 3.02 μs 3.10 μs 2.1973 - 36.49 KB
    StringReader 128.2 μs 1.15 μs 1.02 μs 0.2441 - 7.01 KB
    RawString 127.3 μs 0.91 μs 0.85 μs - - 2.65 KB

    You can see that using an XmlReader is quite a bit slower and much more memory hungry than using the raw string or a StringReader. That itself is unsurprising given how complex it is, but SqlXml over any of those is far worse. A reading of the code makes it clear:

    • SqlXml accepts either a Stream or XmlReader:
      • Stream: creates an XmlReader over it.
      • XmlReader: Rather than just using it like you'd expect, it writes it to a MemoryStream and uses that to create a new XmlReader.
    • The code in SqlParameter.CoerceValue:
      • XmlReader: will stream it over the wire directly.
      • SqlXml: will write it back to a string.

    So if you use SqlXml with a XmlReader then you end up creating the whole XML again twice: once in SqlXml and once in SqlParameter. 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 the XmlReader directly.

  15. AndriySvyryd commented on Jun 29, 2026

    @AndriySvyryd
    Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions