From 47475144347a7df0f546304ec39f063283a900aa Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 16 Aug 2024 17:13:54 +0200 Subject: [PATCH] Add different provider code samples for SqlQuery Closes #2739 --- entity-framework/core/querying/sql-queries.md | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/entity-framework/core/querying/sql-queries.md b/entity-framework/core/querying/sql-queries.md index 2038a7a24c..b412d34bf3 100644 --- a/entity-framework/core/querying/sql-queries.md +++ b/entity-framework/core/querying/sql-queries.md @@ -132,11 +132,42 @@ The following example uses a SQL query that selects from a Table-Valued Function While is useful for querying entities defined in your model, allows you to easily query for scalar, non-entity types via SQL, without needing to drop down to lower-level data access APIs. For example, the following query fetches all the IDs from the `Blogs` table: -[!code-csharp[Main](../../../samples/core/Querying/SqlQueries/Program.cs#SqlQuery)] +```c# +var ids = context.Database + .SqlQuery($"SELECT [BlogId] FROM [Blogs]") + .ToList(); +``` You can also compose LINQ operators over your SQL query. However, since your SQL becomes a subquery whose output column needs to be referenced by the SQL EF adds, you must name the output column `Value`. For example, the following query returns the IDs which are above the ID average: -[!code-csharp[Main](../../../samples/core/Querying/SqlQueries/Program.cs#SqlQueryComposed)] +### [SQL Server](#tab/sqlserver) + +```c# +var overAverageIds = context.Database + .SqlQuery($"SELECT [BlogId] AS [Value] FROM [Blogs]") + .Where(id => id > context.Blogs.Average(b => b.BlogId)) + .ToList(); +``` + +### [Fluent API](#tab/sqlite) + +```c# +var overAverageIds = context.Database + .SqlQuery($"""SELECT "BlogId" AS "Value" FROM "Blogs" """) + .Where(id => id > context.Blogs.Average(b => b.BlogId)) + .ToList(); +``` + +### [Fluent API](#tab/postgres) + +```c# +var overAverageIds = context.Database + .SqlQuery($"""SELECT "BlogId" AS "Value" FROM "Blogs" """) + .Where(id => id > context.Blogs.Average(b => b.BlogId)) + .ToList(); +``` + +*** can be used with any scalar type supported by your database provider. If you'd like to use a type not supported by your database provider, you can use [pre-convention configuration](xref:core/modeling/bulk-configuration#pre-convention-configuration) to define a value conversion for it.