|
8 | 8 | // Load .env |
9 | 9 | Env.Load(); |
10 | 10 |
|
| 11 | +// Update Dapper Type Handler to handle SqlVector<T> |
| 12 | +SqlMapper.AddTypeHandler(new VectorTypeHandler()); |
| 13 | + |
| 14 | +// Get connection string from environment variable |
11 | 15 | var connectionString = Environment.GetEnvironmentVariable("MSSQL"); |
12 | 16 | if (string.IsNullOrWhiteSpace(connectionString)) |
13 | 17 | { |
14 | 18 | Console.WriteLine("Please set the MSSQL environment variable (for example in a .env file). Exiting."); |
15 | 19 | return; |
16 | 20 | } |
17 | 21 |
|
| 22 | +// Create SQL connection |
18 | 23 | await using var connection = new SqlConnection(connectionString); |
19 | | -await connection.OpenAsync(); |
20 | 24 |
|
21 | 25 | // Confirm database project objects exist |
22 | 26 | var tableExists = await connection.ExecuteScalarAsync<int?>( |
|
54 | 58 | { |
55 | 59 | // compute embedding |
56 | 60 | var vector = embeddingClient.GetEmbedding(np.Content); |
57 | | - var sqlVector = new SqlVector<float>(vector); |
58 | 61 |
|
59 | 62 | // check if post exists for this blog |
60 | 63 | var existingPostId = await connection.QuerySingleOrDefaultAsync<int?>( |
61 | 64 | "SELECT PostId FROM dbo.Posts WHERE BlogId = @BlogId and Title = @Title", |
62 | | - new { BlogId = blogId, @Title = np.Title }); |
| 65 | + new { BlogId = blogId, Title = np.Title }); |
63 | 66 |
|
64 | 67 | if (existingPostId.HasValue) |
65 | 68 | { |
66 | 69 | await connection.ExecuteAsync( |
67 | 70 | "UPDATE dbo.Posts SET Content = @Content, Embedding = @Embedding WHERE PostId = @PostId", |
68 | | - new { np.Content, Embedding = sqlVector, PostId = existingPostId.Value } |
| 71 | + new { np.Content, Embedding = vector, PostId = existingPostId.Value } |
69 | 72 | ); |
70 | 73 | } |
71 | 74 | else |
72 | 75 | { |
73 | 76 | await connection.ExecuteAsync( |
74 | 77 | "INSERT INTO dbo.Posts (Title, Content, Embedding, BlogId) VALUES (@Title, @Content, @Embedding, @BlogId)", |
75 | | - new { np.Title, np.Content, Embedding = sqlVector, BlogId = blogId } |
| 78 | + new { np.Title, np.Content, Embedding = vector, BlogId = blogId } |
76 | 79 | ); |
77 | 80 | } |
78 | 81 | } |
79 | 82 |
|
80 | 83 | // Query for similar posts |
81 | 84 | Console.WriteLine("\n----------\n"); |
82 | | -string searchPhrase = "I want to use Azure SQL, EF Core and vectors in my app!"; |
| 85 | +string searchPhrase = "I want to use Azure SQL, Dapper and vectors in my app!"; |
83 | 86 | Console.WriteLine($"Search phrase is: '{searchPhrase}'..."); |
84 | 87 |
|
85 | | -var queryVector = new SqlVector<float>(embeddingClient.GetEmbedding(searchPhrase)); |
| 88 | +var queryVector = embeddingClient.GetEmbedding(searchPhrase); |
86 | 89 |
|
87 | 90 | var sql = @" |
88 | 91 | SELECT TOP (5) p.Title, |
|
0 commit comments