SQL Server: Batched inserts mixing null and non-null SqlVector values fail with error 42211

未关闭
#39,849 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 2 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
csharp, sql

调研方向

Start by reading the SQL Server vector type mapping and parameter configuration code, then compare it with the existing handling referenced in issue #12482. Reproduce the mixed null and non-null vector batch using the supplied test case and inspect how the parameters are typed. Done means batched inserts persist both rows successfully while preserving the vector dimensions and null value.

由索引模型根据 Issue 内容生成。

描述

customer-reported
Bug description

When inserting rows containing both null and non-null SqlVector? values into a vector(1536) column, EF Core generates a multirow MERGE whose null vector parameter is bound as DBNull and inferred as nvarchar, while the populated parameter is bound as vector.

SQL Server then implicitly converts the vector to a string within the VALUES rowset, failing with error 42211: “Truncation of vector is not allowed during the conversion.” The embedding has the correct 1,536 dimensions.

The same rows persist successfully with MaxBatchSize(1), or when the null parameter is explicitly bound as SqlVector.CreateNull(1536).

Seems to appear analogous to #12482.

A quick fix is to have a custom mapping that assigns the correct type to the DBNull values:

internal class SqlServerVectorParameterTypeMappingSource(
	TypeMappingSourceDependencies dependencies,
	RelationalTypeMappingSourceDependencies relationalDependencies,
	ISqlServerSingletonOptions sqlServerSingletonOptions)
	: SqlServerTypeMappingSource(dependencies, relationalDependencies, sqlServerSingletonOptions)
{
	protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
	{
		var mapping = base.FindMapping(mappingInfo);
		return mapping is SqlServerVectorTypeMapping
			? new VectorParameterTypeMapping(mapping.Size).WithTypeMappingInfo(mappingInfo)
			: mapping;
	}

	private sealed class VectorParameterTypeMapping : SqlServerVectorTypeMapping
	{
		public VectorParameterTypeMapping(int? dimensions) : base(dimensions)
		{
		}

		private VectorParameterTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters)
		{
		}

		protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
			=> new VectorParameterTypeMapping(parameters);

		protected override void ConfigureParameter(DbParameter parameter)
		{
			base.ConfigureParameter(parameter);

			var sqlParameter = (SqlParameter)parameter;
			sqlParameter.SqlDbType = Microsoft.Data.SqlDbTypeExtensions.Vector;

			if (sqlParameter.Value is DBNull)
			{
				if (Size is not int dimensions)
				{
					throw new InvalidOperationException("Vector parameters require configured dimensions.");
				}

				sqlParameter.Value = SqlVector<float>.CreateNull(dimensions);
			}
		}
	}
}
Your code
public class VectorParameterReproFixture
    {        
        private readonly string connectionString = "<DB Connection>"

        [Test]
        public async Task MixedVectorBatchFailsButUnbatchedInsertsSucceed()
        {
            await using var connection = new SqlConnection(connectionString);
            await connection.OpenAsync();

            var values = Enumerable.Repeat(0.1234567f, 1536).ToArray();
            TestContext.Progress.WriteLine($"Embedding: {values.Length} dimensions, {JsonSerializer.Serialize(values).Length} JSON characters");
            TestContext.Progress.WriteLine(
                $"EF: {typeof(DbContext).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}; " +
                $"SqlClient: {typeof(SqlConnection).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}");

            await using (var context = new ReproContext(connection, batching: true))
            {
                await context.Database.ExecuteSqlRawAsync(
                    "CREATE TABLE [#VectorParameterRepro] ([Id] INT IDENTITY PRIMARY KEY, " +
                    "[Title] NVARCHAR(MAX) NOT NULL, [Embedding] VECTOR(1536) NULL);");
                AddDocuments(context, values);

                try
                {
                    await context.SaveChangesAsync();
                    Assert.Fail("Expected SQL error 42211 from stock EF's mixed null/vector batch.");
                }
                catch (DbUpdateException error) when (error.InnerException is SqlException { Number: 42211 })
                {
                    TestContext.Progress.WriteLine(error.InnerException.Message);
                }
            }

            await using (var context = new ReproContext(connection, batching: false))
            {
                AddDocuments(context, values);
                await context.SaveChangesAsync();
                var documents = await context.Documents.AsNoTracking().OrderBy(x => x.Id).ToListAsync();
                Assert.That(documents.Count, Is.EqualTo(2));
                Assert.That(documents[0].Embedding.Value.Memory.ToArray(), Is.EqualTo(values));
                Assert.That(documents[1].Embedding, Is.Null);
                TestContext.Progress.WriteLine("MaxBatchSize(1): both rows persisted and read back correctly.");
            }
        }

        private static void AddDocuments(ReproContext context, float[] values)
        {
            context.Documents.AddRange(
                new Document { Title = "Real 1536-dimension vector", Embedding = new SqlVector<float>(values) },
                new Document { Title = "Null vector", Embedding = null });
        }

        private class ReproContext(DbConnection connection, bool batching) : DbContext
        {
            public DbSet<Document> Documents => Set<Document>();

            protected override void OnConfiguring(DbContextOptionsBuilder options)
            {
                options.UseSqlServer(connection, sql =>
                {
                    if (!batching)
                    {
                        sql.MaxBatchSize(1);
                    }
                });
                options.AddInterceptors(new ParameterDiagnostics());
            }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
                => modelBuilder.Entity<Document>().ToTable("#VectorParameterRepro");
        }

        private class Document
        {
            public int Id { get; set; }
            public string Title { get; set; } = string.Empty;

            [Column(TypeName = "vector(1536)")]
            public SqlVector<float>? Embedding { get; set; }
        }

        private class ParameterDiagnostics : DbCommandInterceptor
        {
            public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
                DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
                CancellationToken cancellationToken = default)
            {
                TestContext.Progress.WriteLine(command.CommandText);
                foreach (SqlParameter parameter in command.Parameters)
                {
                    TestContext.Progress.WriteLine(
                        $"{parameter.ParameterName}: {parameter.SqlDbType}, size={parameter.Size}, " +
                        $"null={parameter.Value is DBNull}");
                }

                return ValueTask.FromResult(result);
            }
        }
    }
Stack traces

Verbose output

EF Core version

10.0.13

Database provider

No response

Target framework

.NET 10

Operating system

No response

IDE

No response

主要语言
C#
星标
14.8k
派生
3.5k
平均合并
2 天 22 小时
30 天内合并 PR
158

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

dotnet/efcore 的其他 Issue

查看 dotnet/efcore 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。