Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement EF.Parameter #32427

Merged
merged 1 commit into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions src/EFCore/EF.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,25 @@ public static TProperty Property<TProperty>(
/// Within the context of an EF LINQ query, forces its argument to be inserted into the query as a constant expression. This can be
/// used to e.g. integrate a value as a constant inside an EF query, instead of as a parameter, for query performance reasons.
/// </summary>
/// <remarks>
/// <para>
/// Note that this is a static method accessed through the top-level <see cref="EF" /> static type.
/// </para>
/// <para>
/// See <see href="https://aka.ms/efcore-docs-efproperty">Using EF.Property in EF Core queries</see> for more information and examples.
/// </para>
/// </remarks>
/// <remarks>Note that this is a static method accessed through the top-level <see cref="EF" /> static type.</remarks>
/// <typeparam name="T">The type of the expression to be integrated as a constant into the query.</typeparam>
/// <param name="argument">The expression to be integrated as a constant into the query.</param>
/// <returns>The same value for further use in the query.</returns>
public static T Constant<T>(T argument)
=> throw new InvalidOperationException(CoreStrings.EFConstantInvoked);

/// <summary>
/// Within the context of an EF LINQ query, forces its argument to be inserted into the query as a parameter expression. This can be
/// used to e.g. make sure a constant value is parameterized instead of integrated as a constant into the query, which can be useful
/// in dynamic query construction scenarios.
/// </summary>
/// <remarks>Note that this is a static method accessed through the top-level <see cref="EF" /> static type.</remarks>
/// <typeparam name="T">The type of the expression to be integrated as a parameter into the query.</typeparam>
/// <param name="argument">The expression to be integrated as a parameter into the query.</param>
/// <returns>The same value for further use in the query.</returns>
public static T Parameter<T>(T argument)
=> throw new InvalidOperationException(CoreStrings.EFParameterInvoked);

/// <summary>
/// Provides CLR methods that get translated to database functions when used in LINQ to Entities queries.
/// Calling these methods in other contexts (e.g. LINQ to Objects) will throw a <see cref="NotSupportedException" />.
Expand Down
12 changes: 12 additions & 0 deletions src/EFCore/Properties/CoreStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/EFCore/Properties/CoreStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,9 @@
<data name="EFConstantWithNonEvaluableArgument" xml:space="preserve">
<value>The EF.Constant&lt;T&gt; method may only be used with an argument that can be evaluated client-side and does not contain any reference to database-side entities.</value>
</data>
<data name="EFParameterInvoked" xml:space="preserve">
<value>The EF.Parameter&lt;T&gt; method may only be used within Entity Framework LINQ queries.</value>
</data>
<data name="EmptyComplexType" xml:space="preserve">
<value>Complex type '{complexType}' has no properties defines. Configure at least one property or don't include this type in the model.</value>
</data>
Expand Down
37 changes: 27 additions & 10 deletions src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,18 +178,35 @@ protected override Expression VisitConditional(ConditionalExpression conditional
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Method.DeclaringType == typeof(EF) && methodCallExpression.Method.Name == nameof(EF.Constant))
// If this is a call to EF.Constant(), or EF.Parameter(), then examine the operand; it it's isn't evaluatable (i.e. contains a
// reference to a database table), throw immediately. Otherwise, evaluate the operand (either as a constant or as a parameter) and
// return that.
if (methodCallExpression.Method.DeclaringType == typeof(EF))
{
// If this is a call to EF.Constant(), then examine its operand. If the operand isn't evaluatable (i.e. contains a reference
// to a database table), throw immediately.
// Otherwise, evaluate the operand as a constant and return that.
var operand = methodCallExpression.Arguments[0];
if (!_evaluatableExpressions.TryGetValue(operand, out _))
switch (methodCallExpression.Method.Name)
{
throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluableArgument);
}
case nameof(EF.Constant):
{
var operand = methodCallExpression.Arguments[0];
if (!_evaluatableExpressions.TryGetValue(operand, out _))
{
throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluableArgument);
}

return Evaluate(operand, generateParameter: false);
}

return Evaluate(operand, generateParameter: false);
case nameof(EF.Parameter):
{
var operand = methodCallExpression.Arguments[0];
if (!_evaluatableExpressions.TryGetValue(operand, out _))
{
throw new InvalidOperationException(CoreStrings.EFConstantWithNonEvaluableArgument);
}

return Evaluate(operand, generateParameter: true);
}
}
}

return base.VisitMethodCall(methodCallExpression);
Expand Down Expand Up @@ -686,7 +703,7 @@ private static bool IsEvaluatableNodeType(Expression expression, out bool prefer
case ExpressionType.Call
when expression is MethodCallExpression { Method: var method }
&& method.DeclaringType == typeof(EF)
&& method.Name == nameof(EF.Constant):
&& method.Name is nameof(EF.Constant) or nameof(EF.Parameter):
preferNoEvaluation = true;
return false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2946,6 +2946,55 @@ public override async Task EF_Constant_with_non_evaluatable_argument_throws(bool
AssertSql();
}

public override async Task EF_Parameter(bool async)
{
await base.EF_Parameter(async);

AssertSql(
"""
@__p_0='ALFKI'

SELECT c
FROM root c
WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0))
""");
}

public override async Task EF_Parameter_with_subtree(bool async)
{
await base.EF_Parameter_with_subtree(async);

AssertSql(
"""
@__p_0='ALFKI'

SELECT c
FROM root c
WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0))
""");
}

public override async Task EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(bool async)
{
await base.EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(async);

AssertSql(
"""
@__id_0='ALF'

SELECT c
FROM root c
WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = (@__id_0 || "KI")))
""");
}

public override async Task EF_Parameter_with_non_evaluatable_argument_throws(bool async)
{
await base.EF_Parameter_with_non_evaluatable_argument_throws(async);

AssertSql();
}

private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2393,4 +2393,51 @@ public virtual async Task EF_Constant_with_non_evaluatable_argument_throws(bool

Assert.Equal(CoreStrings.EFConstantWithNonEvaluableArgument, exception.Message);
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task EF_Parameter(bool async)
=> AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => c.CustomerID == EF.Parameter("ALFKI")),
ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALFKI"));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task EF_Parameter_with_subtree(bool async)
{
// This is a somewhat silly scenario: a subtree would get parameterized anyway, with or without EF.Parameter().
// But including for completeness.
var i = "ALF";
var j = "KI";

return AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => c.CustomerID == EF.Parameter(i + j)),
ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALFKI"));
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(bool async)
{
var id = "ALF";

return AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => c.CustomerID == EF.Parameter(id) + "KI"),
ss => ss.Set<Customer>().Where(c => c.CustomerID == "ALF" + "KI"));
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task EF_Parameter_with_non_evaluatable_argument_throws(bool async)
{
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => c.CustomerID == EF.Parameter(c.CustomerID))));

Assert.Equal(CoreStrings.EFConstantWithNonEvaluableArgument, exception.Message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3286,6 +3286,55 @@ public override async Task EF_Constant_with_non_evaluatable_argument_throws(bool
AssertSql();
}

public override async Task EF_Parameter(bool async)
{
await base.EF_Parameter(async);

AssertSql(
"""
@__p_0='ALFKI' (Size = 5) (DbType = StringFixedLength)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__p_0
""");
}

public override async Task EF_Parameter_with_subtree(bool async)
{
await base.EF_Parameter_with_subtree(async);

AssertSql(
"""
@__p_0='ALFKI' (Size = 5) (DbType = StringFixedLength)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__p_0
""");
}

public override async Task EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(bool async)
{
await base.EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(async);

AssertSql(
"""
@__id_0='ALF' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__id_0 + N'KI'
""");
}

public override async Task EF_Parameter_with_non_evaluatable_argument_throws(bool async)
{
await base.EF_Parameter_with_non_evaluatable_argument_throws(async);

AssertSql();
}

private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);

Expand Down
Loading