[英]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?有什么方法可以知道是否从 Package 管理器调用DbContext.OnConfiguring()
?
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.此代码在我的 WinForms 应用程序中运行良好。 However, when adding migrations via the Package Manager Console, DataPath
will be null and an exception is thrown.但是,当通过 Package 管理控制台添加迁移时, DataPath
将为 null 并引发异常。
When run from Package Manager Console, it's okay if DataPath
is null, as no actual database is used in that case.从 Package 管理器控制台运行时,如果DataPath
是 null 也没关系,因为在这种情况下没有使用实际数据库。 But I still want to throw an exception if DataPath
is null while my application is running.但是,如果在我的应用程序运行时DataPath
是 null,我仍然想抛出一个异常。
Is there any way to detect when this code is called from my application, and when it's called from Package Manager Console?有什么方法可以检测何时从我的应用程序调用此代码,何时从 Package 管理器控制台调用它?
Note that I'm using .NET 6 and EF 6.请注意,我使用的是 .NET 6 和 EF 6。
You could get the name of the exe that is running when OnConfiguring
executes with您可以获得执行OnConfiguring
时正在运行的 exe 的名称
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).返回作为默认应用程序域中的进程可执行文件的程序集,或由 ExecuteAssembly(String) 执行的第一个可执行文件。 Can return null when called from unmanaged code.从非托管代码调用时可以返回 null。
See https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getentryassembly for more info有关详细信息,请参阅https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getentryassembly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.