From 3920690c35f7cddebd4b365ad1e5e9726c920922 Mon Sep 17 00:00:00 2001 From: Arthur Vickers Date: Mon, 25 Jul 2022 16:02:10 +0100 Subject: [PATCH] Add a static flag in EF that will be set when code is being executed for design-time discovery Fixes #27306. --- src/EFCore.Design/Design/OperationExecutor.cs | 1 + src/EFCore/EF.cs | 16 ++++++++++++++++ .../Design/OperationExecutorTest.cs | 15 +++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/src/EFCore.Design/Design/OperationExecutor.cs b/src/EFCore.Design/Design/OperationExecutor.cs index f8ea9076ea2..73dae4cbe28 100644 --- a/src/EFCore.Design/Design/OperationExecutor.cs +++ b/src/EFCore.Design/Design/OperationExecutor.cs @@ -697,6 +697,7 @@ public abstract class OperationBase : MarshalByRefObject /// The . protected OperationBase(IOperationResultHandler resultHandler) { + EF.IsDesignTime = true; _resultHandler = resultHandler; } diff --git a/src/EFCore/EF.cs b/src/EFCore/EF.cs index 457cc47efda..57b650f9251 100644 --- a/src/EFCore/EF.cs +++ b/src/EFCore/EF.cs @@ -17,6 +17,22 @@ public static partial class EF internal static readonly MethodInfo PropertyMethod = typeof(EF).GetTypeInfo().GetDeclaredMethod(nameof(Property))!; + /// + /// This flag is set to 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. + /// + /// + /// + /// This flag can be inspected to change application behavior. For example, if the application is being executed by an EF + /// design-time tool, then it may choose to skip executing migrations commands as part of startup. + /// + /// + /// See EF Core command-line reference for more information + /// and examples. + /// + /// + public static bool IsDesignTime { get; set; } + /// /// References a given property or navigation on an entity instance. This is useful for shadow state properties, for /// which no CLR property exists. Currently this method can only be used in LINQ queries and can not be used to diff --git a/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs b/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs index 1b9e1963b31..ce57bf03a06 100644 --- a/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs +++ b/test/EFCore.Design.Tests/Design/OperationExecutorTest.cs @@ -17,6 +17,21 @@ public void Ctor_validates_arguments() public class OperationBaseTests { + [ConditionalFact] + public void Operations_have_design_time_flag_set() + { + var handler = new OperationResultHandler(); + var result = "Twilight Sparkle"; + + new MockOperation(handler, () => + { + Assert.True(EF.IsDesignTime); + return result; + }); + + Assert.Equal(result, handler.Result); + } + [ConditionalFact] public void Execute_catches_exceptions() {