Skip to content

Error when generating a new migration with SqlVector in EF 10 #38162

Closed

Description

@arielmoraes

Bug description

After migrating from EF 9 where some entities had an Embedding using a float[] type, migrations stopped working, with the following error:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindCollectionMapping(RelationalTypeMappingInfo info, Type modelType, Type providerType, CoreTypeMapping elementMapping)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerTypeMappingSource.FindCollectionMapping(RelationalTypeMappingInfo info, Type modelType, Type providerType, CoreTypeMapping elementMapping)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.<>c.<FindMappingWithConversion>b__8_0(ValueTuple`4 k, RelationalTypeMappingSource self)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd[TArg](TKey key, Func`3 valueFactory, TArg factoryArgument)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMappingWithConversion(RelationalTypeMappingInfo mappingInfo, Type providerClrType, ValueConverter customConverter)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMappingWithConversion(RelationalTypeMappingInfo mappingInfo, IReadOnlyList`1 principals)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMapping(IProperty property)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Property.<>c.<get_TypeMapping>b__96_0(IProperty property)
   at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Property.get_TypeMapping()
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Property.Microsoft.EntityFrameworkCore.Metadata.IReadOnlyProperty.FindTypeMapping()
   at Microsoft.EntityFrameworkCore.RelationalPropertyExtensions.FindRelationalTypeMapping(IReadOnlyProperty property)
   at Microsoft.EntityFrameworkCore.RelationalPropertyExtensions.GetColumnType(IReadOnlyProperty property)
   at Microsoft.EntityFrameworkCore.RelationalPropertyExtensions.GetColumnType(IProperty property)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalModel.CreateDefaultColumnMapping(ITypeBase typeBase, ITypeBase mappedType, TableBase defaultTable, TableMappingBase`1 tableMapping, Boolean isTph, Boolean isTpc, IRelationalTypeMappingSource relationalTypeMappingSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalModel.AddDefaultMappings(RelationalModel databaseModel, IEntityType entityType, IRelationalTypeMappingSource relationalTypeMappingSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalModel.Create(IModel model, IRelationalAnnotationProvider relationalAnnotationProvider, IRelationalTypeMappingSource relationalTypeMappingSource, Boolean designTime)
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelRuntimeInitializer.<>c__DisplayClass4_0.<InitializeModel>b__0()
   at Microsoft.EntityFrameworkCore.RelationalModelExtensions.<>c.<GetRelationalModel>b__4_0(Func`1 f)
   at Microsoft.EntityFrameworkCore.Infrastructure.AnnotatableBase.<>c__30`2.<GetOrAddRuntimeAnnotationValue>b__30_0(String n, ValueTuple`3 t)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd[TArg](TKey key, Func`3 valueFactory, TArg factoryArgument)
   at Microsoft.EntityFrameworkCore.Infrastructure.AnnotatableBase.GetOrAddRuntimeAnnotationValue[TValue,TArg](String name, Func`2 valueFactory, TArg factoryArgument)
   at Microsoft.EntityFrameworkCore.RelationalModelExtensions.GetRelationalModel(IModel model)
   at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language, Boolean dryRun)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace, Boolean dryRun)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace, Boolean dryRun)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

My entity was already configured using the fluent API:

builder.Property(e => e.Embedding)
    .HasColumnType("vector(1536)");

The property is now using the SqlVector type:

public SqlVector<float>? Embedding { get; set; }

Am I missing something?

Your code

Code is the same as it was in .NET 9 version, except for the new type that has changed to SqlVector<float>

Stack traces


Verbose output


EF Core version

10.0.7

Database provider

No response

Target framework

.NET 10

Operating system

No response

IDE

VS 2026 18.3.3

Activity

  1. arielmoraes commented on Apr 25, 2026

    @arielmoraes
    Author

    I think I found the problem, I set a breakpoint in the RelationalTypeMappingSource.FindCollectionMapping method and found that the problem was linked to the SqlVector type. The modelType parameter was being passed with the Type String, so EF couldn't find a mapping between String and SqlVector.

    With that finding I went to the ModelSnapshot and the Embedding property was defined as:

    b.PrimitiveCollection<string>("Embedding")
        .HasColumnType("vector(1536)");

    But the new SqlVector type generates the code as:

    b.Property<SqlVector<float>?>("Embedding")
        .HasColumnType("vector(1536)");

    So if someone was using the https://github.com/efcore/EFCore.SqlServer.VectorSearch which @roji built, there will be some problems when trying to migrate. I don't know if there is a better approach, but the workaround I found was to edit the ModelSnapshot manually.

  2. added theissue type on Apr 25, 2026
  3. roji commented on Apr 25, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Summary

    Confirmed bug. A NullReferenceException occurs in RelationalTypeMappingSource.FindCollectionMapping when adding a new migration after upgrading from EF 9 (with the community EFCore.SqlServer.VectorSearch package) to EF 10 (with built-in SqlVector<float> support).

    The old model snapshot contains PrimitiveCollection<string>("Embedding").HasColumnType("vector(1536)") (generated by the community package), while the current model uses SqlVector<float>?. When dotnet ef migrations add runs, the snapshot model is processed without validation (by design, SnapshotModelProcessor.Process passes validationLogger: null), so the ValidatePrimitiveCollection check doesn't run. When the relational model is then created for the snapshot, FindCollectionMapping is called for the string primitive collection with store type vector(1536), and the NRE occurs.

    Root Cause

    In RelationalTypeMappingSource.FindCollectionMapping:

    1. TryFindJsonCollectionMapping returns true for string (since string implements IEnumerable<char>)
    2. FindMapping(info.WithConverter(...)) is called to find a mapping for string with store type vector(1536), but no such mapping exists, so it returns null
    3. The null return value is null-forgivingly dereferenced with !, and .WithComposedConverter() is called on null, causing the NRE

    The same pattern exists in the SQL Server override (SqlServerTypeMappingSource.FindCollectionMapping), which has the same null-dereference risk at line 413.

    Possibly Related Issues

    Minimal repro

    1. Create a new console project and add packages:

    dotnet new console
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.7
    dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.7
    dotnet add package Microsoft.EntityFrameworkCore.Tools --version 10.0.7

    2. Program.cs:

    using Microsoft.Data.SqlTypes;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    await using var context = new TestContext();
    
    public class TestContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer(Environment.GetEnvironmentVariable("Test__SqlServer__DefaultConnection")
                    ?? "Server=.;Database=Test;Trusted_Connection=True;TrustServerCertificate=True")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>(b =>
            {
                b.Property(e => e.Embedding)
                    .HasColumnType("vector(1536)");
            });
        }
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public SqlVector<float>? Embedding { get; set; }
    }

    3. Create Migrations/TestContextModelSnapshot.cs (simulates old snapshot from community package):

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Metadata;
    using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
    
    #nullable disable
    
    namespace efcore_repro_38162.Migrations;
    
    [DbContext(typeof(TestContext))]
    partial class TestContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "9.0.0")
                .HasAnnotation("Relational:MaxIdentifierLength", 128);
    
            SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
    
            modelBuilder.Entity("Blog", b =>
            {
                b.Property<int>("Id")
                    .ValueGeneratedOnAdd()
                    .HasColumnType("int");
    
                SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
    
                b.PrimitiveCollection<string>("Embedding")
                    .HasColumnType("vector(1536)");
    
                b.HasKey("Id");
    
                b.ToTable("Blogs");
            });
        }
    }

    4. Create Migrations/20250101000000_Initial.cs and its Designer file (a matching initial migration).

    5. Run:

    dotnet ef migrations add TestMigration

    Result: System.NullReferenceException: Object reference not set to an instance of an object. at FindCollectionMapping.

    Workaround

    Manually edit the ModelSnapshot file to replace:

    b.PrimitiveCollection<string>("Embedding")
        .HasColumnType("vector(1536)");

    with:

    b.Property<SqlVector<float>?>("Embedding")
        .HasColumnType("vector(1536)");

    (adding using Microsoft.Data.SqlTypes; at the top).

  4. roji commented on Apr 26, 2026

    @roji
    Member

    @AndriySvyryd this seems to be a dup (or very related?) to #33734, but here around the transition from the older SQL Server JSON support (which used string) to the newer (which uses SqlVector<float>). It's probably OK to require users to edit their model snapshots (though if there's a better fix that would obviously be better), but we should at least fix the exception...

    Let me know what you think.

  5. arielmoraes commented on May 2, 2026

    @arielmoraes
    Author

    @roji, the problem seems to be more complex than just editing the ModelSnapshot for generating new migrations. There are some issues when applying migrations.

    The .designer files for each migration also have references to b.PrimitiveCollection<string>("Embedding"), so those must also be edited, otherwise environments that don't have the migration applied yet will have the same problem.

  6. added this to the 11.0.0 milestone on Jun 8, 2026
  7. added a commit that references this issue on Jul 9, 2026
    eac1e40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions