This part discusses how to query SQL database with the defined mapping entities. In EF/Core, LINQ to Entities supports most of the methods provided by Queryable:
The crossed methods are not supported by LINQ to Entities (the list provided by MDSN is not up to date), because they cannot be translated to proper SQL database operations. For example, SQL database has no built-in Zip operation support. Calling these crossed methods throws NotSupportedException at runtime
The underlined methods have some overloads supported by LINQ to Entities, and other overloads not supported:
For GroupBy, Join, GroupJoin, Distinct, Union, Intersect, Except, Contains, the overloads accepting IEqualityComparer parameter are not supported, because apparently IEqualityComparer has no equivalent SQL translation
For OrderBy, ThenBy, OrderByDescending, ThenByDescending, the overloads with IComparer parameter are not supported
For Where, Select, SelectMany, the indexed overloads are not supported
In EF Core, the methods marked with * can execute the query locally in some cases, without being translated to SQL.
EF translate all supported query methods to SQL and executed in database.
For LINQ to Entities, apparently these methods enable fluent method chaining, implement the same LINQ query expression pattern as LINQ to Objects and Parallel LINQ. So in this part, most of the LINQ to Entities queries are demonstrated with query methods.
Similar to the other kinds of LINQ, LINQ to Entities implements deferred execution for these query methods returning IQueryable. The SQL query is translated and executed only when trying to pull the result value from IQueryable for the first time.
EF/Core translates Where query method call to WHERE clause in SQL, and translates the predicate expression tree (again, not predicate function) to the condition in WHERE clause. The following example queries categories with ProductCategoryID greater than 0:
//FROM [Production].[ProductCategory] AS [category]
8
//WHERE [category].[ProductCategoryID] >0
9
}
When WriteLines executes, it pulls the results from the query represented by IQueryable. At this moment, the query is translated to SQL, and executed in database, then SQL execution results are read by EF/Core and yielded.
The C# || operator in the predicate expression tree is translated to SQL OR operator in WHERE clause:
//FROM [Production].[ProductCategory] AS [category]
10
//WHERE ([category].[ProductCategoryID] >0) AND ([category].[ProductCategoryID] <5)
11
}
The other filtering method, OfType, can be used for entity types in inheritance hierarchy. And it is equivalent to Where query with is operator. The following examples both query sales transactions from all transactions:
In EF Core, the above query is translated to a basic SELECT statement without filtering. EF Core executes the translated SQL to query the specified nullable int column of all rows to local, then the int results are locally filtered from all the nullable int results.
EF does not support OfType with primitive type. In EF, the above query throws NotSupportedException: ‘System.Int32’ is not a valid metadata type for type filtering operations. Type filtering is only valid on entity types and complex types.
In above queries, Queryable.Select is not called, and the query results are entities. So in the translated SQL, the SELECT clause queries all the mapped columns in order to construct the result entities. When Select is called, the selector expression tree is translated into SELECT clause. The following example queries persons’ full names by concatenating the first name and last name:
In EF, Select does not support entity type. The above query throws NotSupportedException: The entity or complex type ‘Product’ cannot be constructed in a LINQ to Entities query.
//FROM [Production].[ProductCategory] AS [category]
16
//WHERE [category].[ProductCategoryID] <0
17
// ) AS [t] ON1=1
18
}
In the above query, Where method is translated to SQL query with WHERE clause. Since DefaultIfEmpty should yield at least 1 entity, it is translated to LEFT JOIN with a single row table on a condition that always holds, so that the final query result is guaranteed to have at least 1 row. Here Where filters out all entities, in another word, the right table of LEFT JOIN has no rows, so the LEFT JOIN results 1 row, where all columns are NULL, including primary key. Therefore, DefaultIfEmpty yields a null entity. Besides entity type, DefaultIfEmpty works with primitive type in the same way.
The other DefaultIfEmpty overload accepts a specified default value. EF Core does not translate it to SQL, but execute the query logic locally. For example:
//FROM [Production].[ProductCategory] AS [category]
12
//WHERE [category].[ProductCategoryID] <0
13
}
Here the source query for DefaultIfEmpty is translated to SQL and executed, then EF Core reads the results to local, and detect the results locally. If there is no result row, the specified default value is yielded. DefaultIfEmpty works for specified default primitive value locally too.
In EF, DefaultIfEmpty without default value works with entity type and primitive type. In both cases it is translated to a similar left outer join with a single row. Since EF executes query remotely, the overload with specified default value does not work with entity type, and throws NotSupportedException: Unable to create a constant value of type ‘ProductCategory’. Only primitive types or enumeration types are supported in this context. This overload works with specified default primitive value:
//CASEWHEN ([Project1].[C1] ISNULL) THEN-1ELSE [Project1].[ProductCategoryID] ENDAS [C1]
12
//FROM ( SELECT1AS X ) AS [SingleRowTable1]
13
//LEFT OUTER JOIN (SELECT
14
// [Extent1].[ProductCategoryID] AS [ProductCategoryID],
15
//cast(1astinyint) AS [C1]
16
//FROM [Production].[ProductCategory] AS [Extent1]
17
//WHERE [Extent1].[ProductCategoryID] <0 ) AS [Project1] ON1=1
18
#else
19
//SELECT [category].[ProductCategoryID]
20
//FROM [Production].[ProductCategory] AS [category]
21
//WHERE [category].[ProductCategoryID] <0
22
#endif
23
}
Notice the default value –1 is translated into the remote SQL query. It is the query result if the right table of left outer join is empty. So there is no local query or local detection executed.
Just like in LINQ to Objects, DefaultIfEmpty can also be used to implement outer join, which is discussed later.
//FROM [Production].[ProductSubcategory] AS [subcategory]
10
//ORDER BY [subcategory].[ProductCategoryID]
11
}
EF Core only translates GroupBy an additional ORDER BY clause with the grouping key, so that when reading the SQL execution results to local, the subcategories appears group by group.
EF only supports remote grouping. In EF, the above GroupBy is fully translated to SQL:
1
SELECT
2
[Project2].[ProductCategoryID] AS [ProductCategoryID],
3
[Project2].[C1] AS [C1],
4
[Project2].[Name] AS [Name]
5
FROM ( SELECT
6
[Distinct1].[ProductCategoryID] AS [ProductCategoryID],
[Extent1].[ProductCategoryID] AS [ProductCategoryID]
11
FROM [Production].[ProductSubcategory] AS [Extent1] ) AS [Distinct1]
12
LEFT OUTER JOIN [Production].[ProductSubcategory] AS [Extent2] ON [Distinct1].[ProductCategoryID] = [Extent2].[ProductCategoryID]
13
) AS [Project2]
14
ORDER BY [Project2].[ProductCategoryID] ASC, [Project2].[C1] ASC
It is translated to LEFT OUTER JOIN instead of GROUP BY, because above GroupBy returns hierarchical results (a sequence of groups, where each group is a sequence of results). In the translated SQL, the distinct keys are queried with SELECT DISTINCT. Then these keys left outer joins the rows with LEFT OUTER JOIN, and results all available key-row pairs, which are sorted by key with ORDER BY. So eventually EF reads and yields the results group by group.
When GroupBy returns flattened results (sequence of results), it is translated to GROUP BY clause. This can be done with a GroupBy overload accepting a result selector, or equivalently an additional Select query. The following examples call aggregation query method Count to flatten the results, and they have identical translation:
SelectMany can flatten hierarchical results too. The following GroupBy example does not have aggregation subquery, so it cannot be translated to GROUP BY. It is translated to INNER JOIN::
//INNER JOIN [Production].[TransactionHistory] AS [transaction] ON ([product].[ProductID] = [transaction].[ProductID]) AND ([product].[ListPrice] = ([transaction].[ActualCost] / [transaction].[Quantity]))
23
}
Just like LINQ to Objects, inner join can be done by SelectMany, Select, and GroupJoin as well. In the following example, Select returns hierarchical data, so an additional SelectMany can flatten the result:
The above Select and SelectMany has a Where subquery to filter the related entities to join with. The Where subquery can be substituted by collection navigation property. After the substitution, the queries are translated to the same INNER JOIN as the first Join example:
GroupJoin also returns hierarchical result, so again an additional SelectMany can flatten the result. The following example still has the same INNER JOIN translation as the first Join example:
Navigation property makes it very easy to join entities with relationship. The following example inner joins 3 entity types, where 2 entity types have many-to-many relationship with a junction entity type:
//INNER JOIN [Production].[ProductProductPhoto] AS [product.ProductProductPhotos] ON [product].[ProductID] = [product.ProductProductPhotos].[ProductID]
19
//INNER JOIN [Production].[ProductPhoto] AS [product.ProductProductPhotos.ProductPhoto] ON [product.ProductProductPhotos].[ProductPhotoID] = [product.ProductProductPhotos.ProductPhoto].[ProductPhotoID]
GroupJoin is provided for left outer join. The following example have categories to left outer join subcategories with foreign key, and the results have all categories with or without matching subcategories. It is translated to LEFT JOIN:
//FROM [Production].[ProductCategory] AS [category]
22
//LEFT JOIN [Production].[ProductSubcategory] AS [subcategory] ON [category].[ProductCategoryID] = [subcategory].[ProductCategoryID]
23
//ORDER BY [category].[ProductCategoryID]
24
}
GroupJoin returns hierarchical results. So here the translated SQL also sorts the result by the key, so that EF/Core can read the query results group by group. To have flattened results from GroupJoin, SelectMany can be called. As discussed in the LINQ to Objects chapter, an DefaultIfEmpty subquery is required (It becomes inner join if DefaultIfEmpty is missing). The following example has the same SQL translation as above, it just yields result by result instead of group by group.
Similar to inner join, left outer join can be done with Select and SelectMany too, with a DefaultIfEmpty subquery. The following queries have the same SQL translation:
In EF Core, the above 2 queries are both translated to CROSS APPLY, but this is logically equivalent to LEFT JOIN of the GroupJoin example.
In EF, these translation are the same LEFT OUTER JOIN as previous GroupJoin.
As demonstrated for inner join, in the above Select and SelectMany queries, the Where subquery is equivalent to collection navigation property. EF/Core support collection navigation property for left outer join with Select and SelectMany. The following queries are translated to the same LEFT JOIN query:
//SELECT [category].[Name] AS [Category], [category.ProductSubcategories].[Name] AS [Subcategory]
18
//FROM [Production].[ProductCategory] AS [category]
19
//LEFT JOIN [Production].[ProductSubcategory] AS [category.ProductSubcategories] ON [category].[ProductCategoryID] = [category.ProductSubcategories].[ProductCategoryID]
Just like LINQ to Objects, cross join can be done with SelectMany and Join. The following example queries the expensive products (list price greater than 2000) and cheap products (list price less than 100), and then cross join them to get all possible product bundles, where each bundle has one expensive product and one cheap product:
//WHERE [Extent2].[ListPrice] >cast(2000asdecimal(18))) AS [UnionAll1]
21
#else
22
// ArgumentException: Expression of type'System.Collections.Generic.IEnumerable`1[Product]' cannot be used for parameter of type'System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Storage.ValueBuffer]' of method 'System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Storage.ValueBuffer] Concat[ValueBuffer](System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Storage.ValueBuffer], System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Storage.ValueBuffer])' Parameter name: arg1
23
#endif
24
}
EF Core supports Concat for primitive type, locally. In the above example, Select is called after Concat. It is logically equivalent to call Select before Concat, which works in EF Core:
//FROM [Production].[ProductSubcategory] AS [subcategory]
10
//INNER JOIN [Production].[ProductCategory] AS [subcategory.ProductCategory] ON [subcategory].[ProductCategoryID] = [subcategory.ProductCategory].[ProductCategoryID]
//FROM [Production].[ProductSubcategory] AS [subcategory]
10
//ORDER BY [subcategory].[ProductCategoryID]
11
}
However, as fore mentioned, in EF Core, GroupBy executes locally. The above example only queries grouping keys, however it reads all rows of the table to local, which can be a performance issue.
EF always execute queries remotely, so above GroupBy is properly translated to SELECT DISATINCT query.
GroupBy can also be used for more complex scenarios. The following example queries the full product entities with distinct list price:
Again, EF Core does not translate grouping to SQL. In this example, only 1 entities for each key is queried, but EF Core reads all rows to local, and execute the grouping logic locally.
EF properly translates the above query to SELECT DISTINCT to query the unique keys, then outer applies each key to one row with OUTER APPLY:
1
SELECT
2
[Limit1].[ProductID] AS [ProductID],
3
[Limit1].[Name] AS [Name],
4
[Limit1].[ListPrice] AS [ListPrice],
5
[Limit1].[ProductSubcategoryID] AS [ProductSubcategoryID]
6
FROM (SELECT DISTINCT
7
[Extent1].[ListPrice] AS [ListPrice]
8
FROM [Production].[Product] AS [Extent1] ) AS [Distinct1]
9
OUTERAPPLY (SELECTTOP (1)
10
[Extent2].[ProductID] AS [ProductID],
11
[Extent2].[Name] AS [Name],
12
[Extent2].[ListPrice] AS [ListPrice],
13
[Extent2].[ProductSubcategoryID] AS [ProductSubcategoryID]
14
FROM [Production].[Product] AS [Extent2]
15
WHERE [Distinct1].[ListPrice] = [Extent2].[ListPrice] ) AS [Limit1]
EF Core supports Union for entity and primitive types locally.
EF translates Union to Union ALL with SELECT DISTINCT, so eventually each result is unique.
In SQL, OFFSET is considered to be a part of the ORDER BY clause, so here EF Core generates ORDERBY (SELECT 1) clause.
EF does not automatically generate ORDER BY clause, and the above query throws NotSupportedException: The method ‘Skip’ is only supported for sorted input in LINQ to Entities. The method ‘OrderBy’ must be called before the method ‘Skip’. The following is the equivalent query works in both EF Core and EF:
In EF, similar to GroupBy/Join/GroupJoin, the ordering query methods’ key selector returning anonymous type is properly translated. The above query is translated to:
1
SELECT
2
[Project1].[C1] AS [C1],
3
[Project1].[Name] AS [Name],
4
[Project1].[ListPrice] AS [ListPrice]
5
FROM ( SELECT
6
[Extent1].[Name] AS [Name],
7
[Extent1].[ListPrice] AS [ListPrice],
8
1AS [C1]
9
FROM [Production].[Product] AS [Extent1]
10
) AS [Project1]
11
ORDER BY [Project1].[ListPrice] ASC, [Project1].[Name] ASC
Multiple OrderBy/OrderByDescending calls are translated to SQL reversely. The following example sort all products by list price, then sort all products again by subcategory, which is equivalent to sort all products by subcategory first, then sort products in the same subcategory by list price:
//FROM [Production].[TransactionHistory] AS [product]
11
//WHERE [product].[TransactionType] IN (N'W', N'S', N'P') AND ([product].[ActualCost] >500.0)
12
}
EF Core does not support Cast for primitive type.
EF does not support casting entity type. The above query throws NotSupportedException: Unable to cast the type ‘TransactionHistory’ to type ‘SalesTransactionHistory’. LINQ to Entities only supports casting EDM primitive or enumeration types. EF supports casting primitive type. The following example casts decimal to string, which is translated to CAST function call, casting money to (nvarchar(MAX)):
//CAST( [Extent1].[ListPrice] ASnvarchar(max)) AS [C1]
11
//FROM [Production].[Product] AS [Extent1]
12
#else
13
// InvalidOperationException: No coercion operator is defined between types 'System.Decimal'and'System.String'.
14
#endif
15
}
Queryable has a new query method, AsQueryable, which accepts IEnumerable and returns IQueryable. Remember Enumerable.AsEnumerable can convert more derived sequence (like List, IQueryable, etc.) to IEnumerable. So the Queryable.AsQueryable/Eumerable.AsEnumerable methods look familiar to the ParallelEnumerable.AsParallel/ParallelEnumerable.AsSequential methods, which convert between sequential and parallel local queries at any point. However, AsQueryable/AsEnumerable usually do not convert freely between local and remote queries. The following is the implementation of AsEnumerable and AsQueryable:
AsQueryable accepts an IEnumerable source. If the source is indeed an IQueryable source, then do nothing and just return it; if not, wrap the source into an System.Linq.EnumerableQuery instance, and return it. EnumerableQuery is a special implementation of IQueryable. If an IQueryable query is an EnumerableQuery instance, when this query is executed, it internally calls System.Linq.EnumerableRewriter to translate itself to local query, then execute the translated query locally. For example, AdventureWorks.Products return IQueryable, which is actually a DbSet instance, so calling AsQueryable with AdventureWorks.Products does nothing and returns the DbSet instance itself, which can have its following query method calls to be translated to SQL by EF Core. In contrast, calling AsQueryable with a T[] array returns an EnumerableQuery wrapper, which is a local mocking of remote query and can have its following query methods to be translated to local queries, As a result, AsEnumerable can always convert a remote LINQ to Entities query to local LINQ to Objects query, but AsQueryable cannot always convert arbitrary local LINQ to Objects query to a remote LINQ to Entities query (and logically, an arbitrary local .NET data source cannot be converted to a remote data source like SQL database). For example:
.Select(product => new { Name=product.Name, ListPrice =product.ListPrice }) //Return EntityQueryable<T>.
16
.AsEnumerable() // Do nothing. Directly return the EntityQueryable<T> source.
17
.AsQueryable() // Do nothing. Directly return the EntityQueryable<T> source.
18
.Where(product =>product.ListPrice>0) // Still LINQ to Entities. Return EntityQueryable<T>.
19
.OrderBy(product =>product.Name); // Still LINQ to Entities. Return EntityQueryable<T>.
20
remote.WriteLines();
21
//SELECT [product].[Name], [product].[ListPrice]
22
//FROM [Production].[Product] AS [product]
23
//WHERE [product].[ListPrice] >0.0
24
//ORDER BY [product].[Name]
25
}
In the first query, the LINQ to Entities source is chained with Select, then AsEnumerable returns IEnumerable, so the following Where is Enumerable.Where, and it returns a generator. Then AsQueryable detects if the generator is IQueryable. Since the generator is not IQueryable, AsQueryable returns a EnumerableQuery wrapper, which can have the following OrderBy translated to local query. So in this entire query chaining, only Select, which is before AsEnumerable, can be translated to SQL and executed remotely, all the other query methods are executed locally.
The source is a DbSet instance, which implements IQueryable and represents the LINQ to Entities data source - rows in remote SQL database table.
Queryable.Select is called on DbSet source, in this case it returns a Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable instance in EF Core (System.Data.Entity.DbQuery instance in EF), which implements IQueryable and represents LINQ to Entities query.
Enumerable.AsEnumerable does nothing and directly returns its source, the EntityQueryable (DbQuery for EF) instance
Enumerable.Where is called, since AsEnumerable returns IEnumerable type. Where returns a generator wrapping its source, the EntityQueryable (DbQuery for EF) instance.
Queryable.AsQueryable is called. Its source, the generator from Where, implements IEnumerable, not IQueryable, so AsQueryable return an EnumerableQuery instance wrapping the generator. As fore mentioned, EnumerableQuery has nothing to do with database.
Queryable.OrderBy is called with EnumerableQuery instance, in this case it returns another EnumerableQuery instance, which has nothing to do with database either.
So the first query is a hybrid query. When it is executed, only Select is remote LINQ to Entities query and is translated to SQL. After AsEnumerable, Where goes local, then AsQueryable cannot convert back to remote LINQ to Entities query anymore. So, Where and OrderBy are both local queries, and not translated to SQL.
The second query is a special case, where AsEnumerable is chained with AsQueryable right away. In this case, AsEnumerable and AsQueryable both do nothing at all. The following Where and OrderBy are both LINQ to Entities queries, and translated to SQL along with Select.
In EF, AsEnumerable can be useful for special case. As fore mentioned, in EF, Select does not support entity type. With AsEnumerable, this can be done with LINQ to Objects:
Query methods in this category accepts an IQueryable source and returns a single value. When they are called at the end of a LINQ to Entities query, they executes the query immediately.
In EF, value queries can be used in the subqueries of the above sequence queries. For example, as demonstrated above, the aggregation subquery of GroupBy flattens hierarchical data, which is translated to SQL aggregation function with GROUP BY.
First and FirstOrDefault execute the LINQ to Entities queries immediately. They are translated to TOP(1) filter in the SELECT clause. If a predicate is provided, the predicate is translated to WHERE clause. For example:
As discussed in LINQ to Objects, Single and SingleOrDefault are more strict. They are translated to TOP(2) filter, so that, if there are 0 or more than 1 results, InvalidOperationException is thrown. Similar to First and FirstOrDefault, if a predicate is provided, it is translated to WHERE clause:
Count/LongCount are translated to SQL aggregate functions COUNT/COUNT_BIG. if a is provided, it is translated to WHERE clause. The following examples query the System.Int32 count of categories, and the System.Int64 count of the products with list price greater than 0:
long longCount =source.LongCount(product =>product.ListPrice>0).WriteLine(); //Execute query.
13
//SELECTCOUNT_BIG(*)
14
//FROM [Production].[Product] AS [product]
15
//WHERE [product].[ListPrice] >0.0
16
}
Max/Min/Sum are translated to MAX/MIN/SUM functions. The following examples query the latest ModifiedDate of photos, the lowest list price of products, and the total cost of transactions:
EF does not support Contains for entity type. The above query throws NotSupportedException: Unable to create a constant value of type ‘Product’. Only primitive types or enumeration types are supported in this context.
EF/Core both support Contains for primitive types. In this case, Contains is translated to EXISTS predicate: