SQL Server: Batched inserts mixing null and non-null SqlVector values fail with error 42211
维护者通常 2 天内回复
还没有人认领这个 Issue。
评估
调研方向
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 内容生成。
描述
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
环境准备
在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
dotnet/efcore 的其他 Issue
-
Test bug: Include_collection_with_cross_apply_with_filter relies on nondeterministic ORDER BY with Take可能已有人在做 @Mohamedadel-prog 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 66/100
维护者通常 2 天内回复
-
customer-reported
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 2 天内回复
-
Compiled model: generate a deterministic model ID可能已有人在做 @rgroenewoudt 今天认领。 未关闭
难度 4/5 3-5 天 新手友好度 35/100
维护者通常 2 天内回复
-
难度 4/5 3-5 天 新手友好度 48/100
维护者通常 2 天内回复
-
难度 4/5 3-5 天 新手友好度 35/100
维护者通常 2 天内回复
相似的 Issue
-
area-VM-meta-mono untriaged
难度 2/5 1-3 小时 新手友好度 75/100
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 79/100
BattletechModders/ModTek#256 · 1 条评论 ·
-
难度 2/5 1-3 小时 新手友好度 82/100
microsoft/sqltoolsservice#2851 ·
维护者通常 1 天内回复
-
enhancement
难度 2/5 1-3 小时 新手友好度 68/100
维护者通常 1 天内回复
-
triage/untriaged
难度 2/5 1-3 小时 新手友好度 82/100
unoplatform/uno#26844 ·
维护者通常 1 天内回复