简体   繁体   中英

Any way to detect when DbContext.OnConfiguring() is being called from Package Manager Console?

Is there any way to know if DbContext.OnConfiguring() is being called from the Package Manager?

Here's my method.

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    if (string.IsNullOrWhiteSpace(DataPath))
        throw new InvalidOperationException("No database path is specified.");

    // Configure SQLite
    options.UseSqlite($"Data Source={DataPath}");
}

This code works fine in my WinForms application. However, when adding migrations via the Package Manager Console, DataPath will be null and an exception is thrown.

When run from Package Manager Console, it's okay if DataPath is null, as no actual database is used in that case. But I still want to throw an exception if DataPath is null while my application is running.

Is there any way to detect when this code is called from my application, and when it's called from Package Manager Console?

Note that I'm using .NET 6 and EF 6.

You could get the name of the exe that is running when OnConfiguring executes with

using System.IO;
using System.Reflection;

var exeName = Path.GetFileName(Assembly.GetEntryAssembly().Location);
Console.Log("Running with " + exeName);

Returns the assembly that is the process executable in the default application domain, or the first executable that was executed by ExecuteAssembly(String). Can return null when called from unmanaged code.

See https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getentryassembly for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM