Class LinqOptions
- Namespace
- LinqToDB
- Assembly
- linq2db.dll
public sealed record LinqOptions : IOptionSet, IConfigurationID, IEquatable<LinqOptions>
- Inheritance
-
objectLinqOptions
- Implements
- Extension Methods
Constructors
LinqOptions()
public LinqOptions()
LinqOptions(bool, bool, bool, bool, bool, bool, CompareNulls, bool, bool, TimeSpan?, bool, bool, bool, bool, bool, bool, UpsertEmulationPolicy, EagerLoadingStrategy, ImplicitCollectionLoading, bool, bool, bool)
public LinqOptions(bool PreloadGroups = false, bool IgnoreEmptyUpdate = false, bool GenerateExpressionTest = false, bool TraceMapperExpression = false, bool ConcatenateOrderBy = false, bool OptimizeJoins = true, CompareNulls CompareNulls = CompareNulls.LikeClr, bool GuardGrouping = true, bool DisableQueryCache = false, TimeSpan? CacheSlidingExpiration = null, bool PreferApply = true, bool KeepDistinctOrdered = true, bool ParameterizeTakeSkip = true, bool EnableContextSchemaEdit = false, bool PreferExistsForScalar = false, bool PreferClientCalculation = false, UpsertEmulationPolicy UpsertEmulationPolicy = UpsertEmulationPolicy.Allow, EagerLoadingStrategy DefaultEagerLoadingStrategy = EagerLoadingStrategy.Default, ImplicitCollectionLoading ImplicitCollectionLoading = ImplicitCollectionLoading.Allow, bool OptimizeForSequentialAccess = false, bool UseDbBatch = true, bool UseCombinedCommands = false)
Parameters
PreloadGroupsboolControls how group data for LINQ queries ended with GroupBy will be loaded:
- if true - group data will be loaded together with main query, resulting in 1 + N queries, where N - number of groups;
- if false - group data will be loaded when you call enumerator for specific group IGrouping<TKey, TElement>. Default value: false.
IgnoreEmptyUpdateboolControls behavior of linq2db when there is no updateable fields in Update query:
- if true - query not executed and Update operation returns 0 as number of affected records;
- if false - LinqToDBException will be thrown. Default value: false.
GenerateExpressionTestboolEnables generation of test class for each LINQ query, executed while this option is enabled. This option could be useful for issue reporting, when you need to provide reproducible case. Test file will be placed to
linq2dbsubfolder of temp folder and exact file path will be logged to data connection tracing infrastructure. See TraceSwitch for more details. Default value: false.TraceMapperExpressionboolEnables logging of generated mapping expression to data connection tracing infrastructure. See TraceSwitch for more details. Default value: false.
ConcatenateOrderByboolControls behavior, when LINQ query chain contains multiple OrderBy<TSource, TKey>(IQueryable<TSource>, Expression<Func<TSource, TKey>>) or OrderByDescending<TSource, TKey>(IQueryable<TSource>, Expression<Func<TSource, TKey>>) calls:
OptimizeJoinsboolIf enabled, linq2db will try to reduce number of generated SQL JOINs for LINQ query. Attempted optimizations:
- removes duplicate joins by unique target table key;
- removes self-joins by unique key;
- removes left joins if joined table is not used in query. Default value: true.
CompareNullsCompareNullsIf set to LikeClr nullable fields would be checked for IS NULLin Equal/NotEqual comparisons. If set to LikeSql comparisons are compiled straight to equivalent SQL operators, which consider nulls values as not equal. LikeSqlExceptParameters is a backward compatible option that works mostly as LikeSql, but sniffs parameters value and changes = intoIS NULLwhen parameters are null. Comparisons to literal null are always compiled intoIS NULL. This affects: Equal, NotEqual, Not Contains Default value: LikeClr.public class MyEntity { public int? Value; } db.MyEntity.Where(e => e.Value != 10) from e1 in db.MyEntity join e2 in db.MyEntity on e1.Value equals e2.Value select e1 var filter = new [] {1, 2, 3}; db.MyEntity.Where(e => ! filter.Contains(e.Value))Would be converted to next queries under LikeClr:
SELECT Value FROM MyEntity WHERE Value IS NULL OR Value != 10 SELECT e1.Value FROM MyEntity e1 INNER JOIN MyEntity e2 ON e1.Value = e2.Value OR (e1.Value IS NULL AND e2.Value IS NULL) SELECT Value FROM MyEntity WHERE Value IS NULL OR NOT Value IN (1, 2, 3)GuardGroupingboolControls behavior of LINQ query, which ends with GroupBy call. - if true - LinqToDBException will be thrown for such queries; - if false - eager loading used. Default value: true. More details. DisableQueryCacheboolUsed to disable LINQ expressions caching for queries. This cache reduces time, required for query parsing but have several side-effects: - cached LINQ expressions could contain references to external objects as parameters, which could lead to memory leaks if those objects are not used anymore by other code
- cache access synchronization could lead to bigger latencies than it saves.
Default value: false.
It is not recommended to enable this option as it could lead to severe slowdown. Better approach will be to use NoLinqCache scope around queries, that produce severe memory leaks you need to fix.
More details.CacheSlidingExpirationTimeSpan?Specifies timeout when query will be evicted from cache since last execution of query. Default value is 1 hour.
PreferApplyboolUsed to generate CROSS APPLY or OUTER APPLY if possible. Default value: true.
KeepDistinctOrderedboolAllows SQL generation to automatically transform
SELECT DISTINCT value FROM Table ORDER BY dateInto GROUP BY equivalent if syntax is not supported Default value: true.
ParameterizeTakeSkipboolEnables Take/Skip parameterization. Default value: true.
EnableContextSchemaEditboolIf true, user could add new mappings to context mapping schems (MappingSchema). Otherwise, LinqToDBException will be generated on locked mapping schema edit attempt. It is not recommended to enable this option as it has performance implications. Proper approach is to create single MappingSchema instance once, configure mappings for it and use this MappingSchema instance for all context instances. Default value: false.
PreferExistsForScalarboolIf true, EXISTS operator will be generated instead of IN operator for scalar values.
SELECT Value FROM MyEntity e WHERE EXISTS(SELECT * FROM MyEntity2 e2 WHERE e2.Value = e.Value)vs
SELECT Value FROM MyEntity e WHERE Value IN (SELECT Value FROM MyEntity2 e2)Default value: false.
PreferClientCalculationboolWhen enabled, computed expressions in the final projection (arithmetic, conditionals, unary operations, and mapped members/methods that do not prefer server-side evaluation) are calculated on the client during materialization instead of being translated into additional SQL columns. Real database columns, already-built subqueries, and expressions that prefer or require server-side evaluation (for example, members or methods mapped with PreferServerSide or ServerSideOnly) are still translated to SQL. Default value: false.
UpsertEmulationPolicyUpsertEmulationPolicyControls what happens when an
Upsertcannot be expressed as a native single-statement upsert orMERGEfor the target provider and would fall back to an emulated multi-statementSELECT → UPDATE → INSERTsequence (the three statements run as independent commands — wrap the call in a transaction if atomicity is required).- Allow (default) — perform the emulated fallback.
- Throw — reject it with LinqToDBException at build time.
DefaultEagerLoadingStrategyEagerLoadingStrategySpecifies the default EagerLoadingStrategy used for all LoadWith/ThenLoad eager-loading operations when no per-query strategy is set via
WithUnionLoadStrategy,WithKeyedLoadStrategy, orWithSeparateLoadStrategy. Default value: Default.ImplicitCollectionLoadingImplicitCollectionLoadingWith Throw, a query that triggers an implicit eager load — a collection projected in a
Selectwithout being explicitly requested — throws LinqToDBException at build time; with Allow (the default) it is loaded as usual.The guard is bypassed when the eager load is explicit:
LoadWith/ThenLoadallows that one collection (other unmarked collections in the same query still throw), while a rootWithUnionLoadStrategy/WithKeyedLoadStrategy/WithSeparateLoadStrategymarker opts the whole query in.OptimizeForSequentialAccessboolEnables mapping expression to be compatible with SequentialAccess behavior. Note that it doesn't switch linq2db to use SequentialAccess behavior for queries, so this optimization could be used for Default too. Default value: false.
UseDbBatchboolWhen enabled and the provider supports the ADO.NET batching API (
DbConnection.CanCreateBatch), combined multi-statement execution (for example eager loading run as one round-trip) is sent as aDbBatch— each statement carrying its own parameters — instead of one semicolon-concatenated command. Falls back to the concatenated command when the provider cannot batch, on target frameworks without the API (net462/netstandard2.0), or when an ICommandInterceptor is registered (batched commands bypass command interceptors). Default value: true.UseCombinedCommandsboolMaster switch for combined multi-statement execution: sending several statements of one logical operation as a single database round-trip and reading their result sets in order. It drives both consumers — eager loading (a main query plus its child collections collapse from N+1 round-trips to 1) and multi-step DML.
Off by default in 6.x because enabling it is observable, not merely faster: the emitted SQL changes shape (statements joined by
;, sharing one parameter scope with deduplicated names), and with UseDbBatch the command travels a different ADO.NET path, which changes traced output. The implicit read-consistency transaction (DefaultMultiQueryIsolationLevel) is unchanged: a sequential eager load already opens one whenever the query has harvesters. Planned to default to true in version 7.Still bounded by provider capability — a provider that does not report IsMultiStatementBatchSupported and IsMultipleResultSetsSupported stays sequential regardless of this option. UseDbBatch selects the backend wherever statements are combined.
A query that runs while the context carries pending query hints stays sequential, eager load and multi-step DML alike: a hint applies to one command. An eager load also stays sequential when the context's type overrides
DataConnection.ProcessQuery, which is applied by the per-command path the combined executor replaces, so combining would drop it from part of the load rather than all of it. Eager loads are combined only when the query runs on a DataConnection or a DataContext (a remote context loads them sequentially), and never for a compiled query that returns a single element; children loaded by the KeyedQuery strategy always run as separate commands. Multi-step DML is combined on every context, a remote one included.Default value: false.
Properties
CacheSlidingExpiration
Specifies timeout when query will be evicted from cache since last execution of query. Default value is 1 hour.
public TimeSpan? CacheSlidingExpiration { get; init; }
Property Value
CacheSlidingExpirationOrDefault
public TimeSpan CacheSlidingExpirationOrDefault { get; }
Property Value
CompareNulls
IS NULL in Equal/NotEqual comparisons.
If set to LikeSql comparisons are compiled straight to equivalent SQL operators,
which consider nulls values as not equal.
LikeSqlExceptParameters is a backward compatible option that works mostly as LikeSql,
but sniffs parameters value and changes = into IS NULL when parameters are null.
Comparisons to literal null are always compiled into IS NULL.
This affects: Equal, NotEqual, Not Contains
Default value: LikeClr.
public class MyEntity
{
public int? Value;
}
db.MyEntity.Where(e => e.Value != 10)
from e1 in db.MyEntity
join e2 in db.MyEntity on e1.Value equals e2.Value
select e1
var filter = new [] {1, 2, 3};
db.MyEntity.Where(e => ! filter.Contains(e.Value))
Would be converted to next queries under LikeClr:
SELECT Value FROM MyEntity WHERE Value IS NULL OR Value != 10
SELECT e1.Value
FROM MyEntity e1
INNER JOIN MyEntity e2 ON e1.Value = e2.Value OR (e1.Value IS NULL AND e2.Value IS NULL)
SELECT Value FROM MyEntity WHERE Value IS NULL OR NOT Value IN (1, 2, 3)
public CompareNulls CompareNulls { get; init; }
Property Value
ConcatenateOrderBy
Controls behavior, when LINQ query chain contains multiple OrderBy<TSource, TKey>(IQueryable<TSource>, Expression<Func<TSource, TKey>>) or OrderByDescending<TSource, TKey>(IQueryable<TSource>, Expression<Func<TSource, TKey>>) calls:
public bool ConcatenateOrderBy { get; init; }
Property Value
Default
Gets default LinqOptions instance.
public static LinqOptions Default { get; set; }
Property Value
DefaultEagerLoadingStrategy
Specifies the default EagerLoadingStrategy used for all LoadWith/ThenLoad eager-loading
operations when no per-query strategy is set via WithUnionLoadStrategy, WithKeyedLoadStrategy, or WithSeparateLoadStrategy.
Default value: Default.
public EagerLoadingStrategy DefaultEagerLoadingStrategy { get; init; }
Property Value
DisableQueryCache
- cached LINQ expressions could contain references to external objects as parameters, which could lead to memory leaks if those objects are not used anymore by other code
- cache access synchronization could lead to bigger latencies than it saves.
Default value: false.
It is not recommended to enable this option as it could lead to severe slowdown. Better approach will be to use NoLinqCache scope around queries, that produce severe memory leaks you need to fix.
More details.public bool DisableQueryCache { get; init; }
Property Value
EnableContextSchemaEdit
If true, user could add new mappings to context mapping schems (MappingSchema). Otherwise, LinqToDBException will be generated on locked mapping schema edit attempt. It is not recommended to enable this option as it has performance implications. Proper approach is to create single MappingSchema instance once, configure mappings for it and use this MappingSchema instance for all context instances. Default value: false.
public bool EnableContextSchemaEdit { get; init; }
Property Value
GenerateExpressionTest
Enables generation of test class for each LINQ query, executed while this option is enabled.
This option could be useful for issue reporting, when you need to provide reproducible case.
Test file will be placed to linq2db subfolder of temp folder and exact file path will be logged
to data connection tracing infrastructure.
See TraceSwitch for more details.
Default value: false.
public bool GenerateExpressionTest { get; init; }
Property Value
GuardGrouping
public bool GuardGrouping { get; init; }
Property Value
IgnoreEmptyUpdate
Controls behavior of linq2db when there is no updateable fields in Update query:
- if true - query not executed and Update operation returns 0 as number of affected records;
- if false - LinqToDBException will be thrown. Default value: false.
public bool IgnoreEmptyUpdate { get; init; }
Property Value
ImplicitCollectionLoading
With Throw, a query that triggers an implicit eager load — a collection projected
in a Select without being explicitly requested — throws LinqToDBException at
build time; with Allow (the default) it is loaded as usual.
The guard is bypassed when the eager load is explicit: LoadWith/ThenLoad allows that
one collection (other unmarked collections in the same query still throw), while a root
WithUnionLoadStrategy/WithKeyedLoadStrategy/WithSeparateLoadStrategy marker opts
the whole query in.
public ImplicitCollectionLoading ImplicitCollectionLoading { get; init; }
Property Value
OptimizeForSequentialAccess
Enables mapping expression to be compatible with SequentialAccess behavior. Note that it doesn't switch linq2db to use SequentialAccess behavior for queries, so this optimization could be used for Default too. Default value: false.
public bool OptimizeForSequentialAccess { get; init; }
Property Value
OptimizeJoins
If enabled, linq2db will try to reduce number of generated SQL JOINs for LINQ query. Attempted optimizations:
- removes duplicate joins by unique target table key;
- removes self-joins by unique key;
- removes left joins if joined table is not used in query. Default value: true.
public bool OptimizeJoins { get; init; }
Property Value
ParameterizeTakeSkip
Enables Take/Skip parameterization. Default value: true.
public bool ParameterizeTakeSkip { get; init; }
Property Value
PreferClientCalculation
When enabled, computed expressions in the final projection (arithmetic, conditionals, unary operations, and mapped members/methods that do not prefer server-side evaluation) are calculated on the client during materialization instead of being translated into additional SQL columns. Real database columns, already-built subqueries, and expressions that prefer or require server-side evaluation (for example, members or methods mapped with PreferServerSide or ServerSideOnly) are still translated to SQL. Default value: false.
public bool PreferClientCalculation { get; init; }
Property Value
PreferExistsForScalar
If true, EXISTS operator will be generated instead of IN operator for scalar values.
SELECT Value FROM MyEntity e WHERE EXISTS(SELECT * FROM MyEntity2 e2 WHERE e2.Value = e.Value)
vs
SELECT Value FROM MyEntity e WHERE Value IN (SELECT Value FROM MyEntity2 e2)
Default value: false.
public bool PreferExistsForScalar { get; init; }
Property Value
TraceMapperExpression
Enables logging of generated mapping expression to data connection tracing infrastructure. See TraceSwitch for more details. Default value: false.
public bool TraceMapperExpression { get; init; }
Property Value
UpsertEmulationPolicy
Controls what happens when an Upsert cannot be expressed as a native single-statement upsert
or MERGE for the target provider and would fall back to an emulated multi-statement
SELECT → UPDATE → INSERT sequence (the three statements run as independent commands — wrap the
call in a transaction if atomicity is required).
- Allow (default) — perform the emulated fallback.
- Throw — reject it with LinqToDBException at build time.
public UpsertEmulationPolicy UpsertEmulationPolicy { get; init; }
Property Value
UseCombinedCommands
Master switch for combined multi-statement execution: sending several statements of one logical operation as a single database round-trip and reading their result sets in order. It drives both consumers — eager loading (a main query plus its child collections collapse from N+1 round-trips to 1) and multi-step DML.
Off by default in 6.x because enabling it is observable, not merely faster: the emitted SQL changes shape
(statements joined by ;, sharing one parameter scope with deduplicated names), and with
UseDbBatch the command travels a different ADO.NET path, which changes traced output. The implicit
read-consistency transaction (DefaultMultiQueryIsolationLevel)
is unchanged: a sequential eager load already opens one whenever the query has harvesters. Planned to default to
true in version 7.
Still bounded by provider capability — a provider that does not report IsMultiStatementBatchSupported and IsMultipleResultSetsSupported stays sequential regardless of this option. UseDbBatch selects the backend wherever statements are combined.
A query that runs while the context carries pending query hints stays sequential, eager load and multi-step DML
alike: a hint applies to one command. An eager load also stays sequential when the context's type overrides
DataConnection.ProcessQuery, which is applied by the per-command path the combined executor replaces, so
combining would drop it from part of the load rather than all of it. Eager loads are combined only when the query
runs on a DataConnection or a DataContext (a remote context
loads them sequentially), and never for a compiled query that returns a single element; children loaded by the
KeyedQuery strategy always run as separate commands. Multi-step DML is combined on every context, a remote one
included.
Default value: false.
public bool UseCombinedCommands { get; init; }
Property Value
UseDbBatch
When enabled and the provider supports the ADO.NET batching API (DbConnection.CanCreateBatch),
combined multi-statement execution (for example eager loading run as one round-trip) is sent as a
DbBatch — each statement carrying its own parameters — instead of one
semicolon-concatenated command. Falls back to the concatenated command when the provider cannot batch, on target
frameworks without the API (net462/netstandard2.0), or when an ICommandInterceptor
is registered (batched commands bypass command interceptors).
Default value: true.
public bool UseDbBatch { get; init; }
Property Value
Methods
Equals(LinqOptions?)
Indicates whether the current object is equal to another object of the same type.
public bool Equals(LinqOptions? other)
Parameters
otherLinqOptionsAn object to compare with this object.
Returns
GetHashCode()
Serves as the default hash function.
public override int GetHashCode()
Returns
- int
A hash code for the current object.