Skip to content

Commit

Permalink
ExecuteUpdate: Implement support for DEFAULT (#28784)
Browse files Browse the repository at this point in the history
Resolves #28660
  • Loading branch information
smitpatel authored Aug 19, 2022
1 parent 4b6010e commit 63bb844
Show file tree
Hide file tree
Showing 12 changed files with 113 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,12 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp
}
}

// EF.Default
if (methodCallExpression.Method.IsEFDefaultMethod())
{
return new SqlFragmentExpression("DEFAULT");
}

var method = methodCallExpression.Method;
var arguments = methodCallExpression.Arguments;
EnumerableExpression? enumerableExpression = null;
Expand Down
8 changes: 7 additions & 1 deletion src/EFCore.Sqlite.Core/Properties/SqliteStrings.Designer.cs

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

5 changes: 4 additions & 1 deletion src/EFCore.Sqlite.Core/Properties/SqliteStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@
<data name="ApplyNotSupported" xml:space="preserve">
<value>Translating this query requires the SQL APPLY operation, which is not supported on SQLite.</value>
</data>
<data name="DefaultNotSupported" xml:space="preserve">
<value>Translating this operation requires the 'DEFAULT', which is not supported on SQLite.</value>
</data>
<data name="DuplicateColumnNameSridMismatch" xml:space="preserve">
<value>'{entityType1}.{property1}' and '{entityType2}.{property2}' are both mapped to column '{columnName}' in '{table}', but are configured with different SRIDs.</value>
</data>
Expand Down Expand Up @@ -201,4 +204,4 @@
<data name="StoredProceduresNotSupported" xml:space="preserve">
<value>SQLite does not support stored procedures, but one has been configured on entity type '{entityType}'. See http://go.microsoft.com/fwlink/?LinkId=723262 for more information and examples.</value>
</data>
</root>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Sqlite.Internal;

namespace Microsoft.EntityFrameworkCore.Sqlite.Query.Internal;

Expand Down Expand Up @@ -211,6 +212,24 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
return visitedExpression;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
// EF.Default
if (methodCallExpression.Method.IsEFDefaultMethod())
{
AddTranslationErrorDetails(SqliteStrings.DefaultNotSupported);
return QueryCompilationContext.NotTranslatedExpression;
}

return base.VisitMethodCall(methodCallExpression);
}

private static Type? GetProviderType(SqlExpression? expression)
=> expression == null
? null
Expand Down
17 changes: 17 additions & 0 deletions src/EFCore/EF.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ public static partial class EF
internal static readonly MethodInfo PropertyMethod
= typeof(EF).GetTypeInfo().GetDeclaredMethod(nameof(Property))!;

internal static readonly MethodInfo DefaultMethod
= typeof(EF).GetTypeInfo().GetDeclaredMethod(nameof(Default))!;

/// <summary>
/// This flag is set to <see langword="true" /> when code is being run from a design-time tool, such
/// as "dotnet ef" or one of the Package Manager Console PowerShell commands "Add-Migration", "Update-Database", etc.
Expand Down Expand Up @@ -55,6 +58,20 @@ public static TProperty Property<TProperty>(
[NotParameterized] string propertyName)
=> throw new InvalidOperationException(CoreStrings.PropertyMethodInvoked);

/// <summary>
/// Used set a property to its default value within <see cref="M:RelationalQueryableExtensions.ExecuteUpdate" /> or
/// <see cref="M:RelationalQueryableExtensions.ExecuteUpdateAsync" />.
/// </summary>
/// <remarks>
/// Depending on how the property is configured, this may be <see langword="null" />, or another value defined via
/// <see cref="M:RelationalPropertyBuilderExtensions.HasDefaultValue" /> or similar.
/// </remarks>
/// <typeparam name="T">The type of the property being set.</typeparam>
/// <returns>The default value of the property.</returns>
public static T Default<T>()
// TODO: Update exception message
=> throw new InvalidOperationException(CoreStrings.DefaultMethodInvoked);

/// <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
27 changes: 20 additions & 7 deletions src/EFCore/Infrastructure/MethodInfoExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,24 @@ public static class MethodInfoExtensions
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns><see langword="true" /> if the method is <see cref="EF.Property{TProperty}" />; <see langword="false" /> otherwise.</returns>
public static bool IsEFPropertyMethod(this MethodInfo? methodInfo)
=> Equals(methodInfo, EF.PropertyMethod)
// fallback to string comparison because MethodInfo.Equals is not
// always true in .NET Native even if methods are the same
|| methodInfo?.IsGenericMethod == true
&& methodInfo.Name == nameof(EF.Property)
&& methodInfo.DeclaringType?.FullName == EFTypeName;
public static bool IsEFPropertyMethod(this MethodInfo methodInfo)
=> methodInfo.IsGenericMethod
&& (Equals(methodInfo.GetGenericMethodDefinition(), EF.PropertyMethod)
// fallback to string comparison because MethodInfo.Equals is not
// always true in .NET Native even if methods are the same
|| (methodInfo.Name == nameof(EF.Property)
&& methodInfo.DeclaringType?.FullName == EFTypeName));

/// <summary>
/// Returns <see langword="true" /> if the given method is <see cref="EF.Default{T}" />.
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns><see langword="true" /> if the method is <see cref="EF.Default{T}" />; <see langword="false" /> otherwise.</returns>
public static bool IsEFDefaultMethod(this MethodInfo methodInfo)
=> methodInfo.IsGenericMethod
&& (Equals(methodInfo.GetGenericMethodDefinition(), EF.DefaultMethod)
// fallback to string comparison because MethodInfo.Equals is not
// always true in .NET Native even if methods are the same
|| (methodInfo.Name == nameof(EF.DefaultMethod)
&& methodInfo.DeclaringType?.FullName == EFTypeName));
}
6 changes: 6 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 @@ -336,6 +336,9 @@
<data name="DebugViewQueryStringError" xml:space="preserve">
<value>Error creating query string: {message}.</value>
</data>
<data name="DefaultMethodInvoked" xml:space="preserve">
<value>The EF.Default&lt;T&gt; property may only be used within Entity Framework ExecuteUpdate method.</value>
</data>
<data name="DeleteBehaviorAttributeNotOnNavigationProperty" xml:space="preserve">
<value>The [DeleteBehavior] attribute may only be specified on navigation properties, and is not supported not on properties making up the foreign key.</value>
</data>
Expand Down
3 changes: 2 additions & 1 deletion src/EFCore/Query/EvaluatableExpressionFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ public virtual bool IsEvaluatableExpression(Expression expression, IModel model)
|| Equals(method, RandomNextNoArgs)
|| Equals(method, RandomNextOneArg)
|| Equals(method, RandomNextTwoArgs)
|| method.DeclaringType == typeof(DbFunctionsExtensions))
|| method.DeclaringType == typeof(DbFunctionsExtensions)
|| method.IsEFDefaultMethod())
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,17 @@ public virtual Task Update_Where_set_constant(bool async)
rowsAffectedCount: 8,
(b, a) => Assert.All(a, c => Assert.Equal("Updated", c.ContactName)));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Update_Where_set_default(bool async)
=> AssertUpdate(
async,
ss => ss.Set<Customer>().Where(c => c.CustomerID.StartsWith("F")),
e => e,
s => s.SetProperty(c => c.ContactName, c => EF.Default<string>()),
rowsAffectedCount: 8,
(b, a) => Assert.All(a, c => Assert.Null(c.ContactName)));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Update_Where_parameter_set_constant(bool async)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,17 @@ FROM [Customers] AS [c]
WHERE [c].[CustomerID] LIKE N'F%'");
}

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

AssertExecuteUpdateSql(
@"UPDATE [c]
SET [c].[ContactName] = DEFAULT
FROM [Customers] AS [c]
WHERE [c].[CustomerID] LIKE N'F%'");
}

public override async Task Update_Where_parameter_set_constant(bool async)
{
await base.Update_Where_parameter_set_constant(async);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Sqlite.Internal;

namespace Microsoft.EntityFrameworkCore.BulkUpdates;
Expand Down Expand Up @@ -549,6 +550,12 @@ public override async Task Update_Where_set_constant(bool async)
WHERE ""c"".""CustomerID"" LIKE 'F%'");
}

public override Task Update_Where_set_default(bool async)
=> AssertTranslationFailed(
RelationalStrings.UnableToTranslateSetProperty(
"c => c.ContactName", "c => EF.Default<string>()", SqliteStrings.DefaultNotSupported),
() => base.Update_Where_set_default(async));

public override async Task Update_Where_parameter_set_constant(bool async)
{
await base.Update_Where_parameter_set_constant(async);
Expand Down

0 comments on commit 63bb844

Please sign in to comment.