Using the new SqlVector type with EF Core and Dapper

Wait 5 sec.

Azure SQL vector support has been generally available for a few months now, and the ecosystem is quickly evolving to make working with vectors in your applications as seamless and efficient as possible.With the release of Microsoft.Data.SqlClient 6.1, developers can now take advantage of binary transport for vector data via the new SqlVector class. This significantly improves performance when moving vectors between your application and the database, laying the groundwork for optimized vector handling in popular .NET libraries like: EF Core 9 EF Core 10 DapperHere’s how you can start using SqlVector in each of these libraries:EF Core 9To enable binary vector transfer in EF Core 9, make sure to use the appropriate extension EFCore.SqlServer.VectorSearch. Just add the package and configure your model to use SqlVector:builder.Services.AddDbContext(options => options.UseSqlServer("", o => o.UseVectorSearch()));then tell EF Core what property of your POCO object should use the vector type:protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity().Property(p => p.Embedding).HasColumnType("vector(1536)");}and you're good to go! The extension also add support for EF.Functions.VectorDistance for using VECTOR_DISTANCE in T-SQL to find closest vectors to a given query vector.EF Core 10EF Core 10 introduces native support for SqlVector, making it even easier to work with vector data. You can store and manipulate vectors and use the VECTOR_DISTANCE function via the new EF.Functions.VectorDistance() method in your LINQ queries. Just tell EF Core what property is mapped to a vector, and it is done:public class Blog{ // ... [Column(TypeName = "vector(1536)")] public SqlVector Embedding { get; set; }}DapperNo need to wait for a Dapper update! Since Dapper builds on top of SqlClient, you can register a custom Type Handler to map float[] or ReadOnlyMemory to use SqlVector seamlessly:public class VectorTypeHandler: SqlMapper.TypeHandler{ public override float[] Parse(object value) { return ((SqlVector)value).Memory.ToArray(); } public override void SetValue(System.Data.IDbDataParameter parameter, float[]? value) { parameter.Value = value is not null ? new SqlVector(value) : DBNull.Value; ((SqlParameter)parameter).SqlDbType = SqlDbTypeExtensions.Vector; }}ConclusionsThat’s it! With just a few lines of code, you can unlock high-performance vector operations in your .NET applications. Fast, easy, and future-ready. The end-to-end samples for all the mentioned libraries are available in the following GitHub repo:https://github.com/Azure-Samples/azure-sql-db-vector-search/tree/main/DotNet