Skip to content

xml constants do not have the N prefix #38429

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

Metadata

Metadata

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions