gpt4 book ai didi

c# - 没有无参数 DbContext 和 DbContextFactory 构造函数的添加迁移

转载 作者:太空狗 更新时间:2023-10-29 23:29:04 25 4
gpt4 key购买 nike

我的应用程序在 DbContext 处没有无参数构造函数实现,我不喜欢为 IDbContextFactory<> 提供无参数构造函数实现。

原因是我想控制 DbContext 指向的位置。这就是为什么我所有的构造函数都会请求 ConnectionStringProvider。

public class MyDbContext : DbContext
{
internal MyDbContext(IConnectionStringProvider provider) : base(provider.ConnectionString) {}
}

public class MyContextFactory : IDbContextFactory<MyDbContext>
{
private readonly IConnectionStringProvider _provider;
public MyContextFactory(IConnectionStringProvider provider)
{
_provider = provider;
}
public MyDbContext Create()
{
return new MyDbContext(_provider.ConnectionString);
}
}

我绝对不想添加默认构造函数!我已经这样做了,但由于错误的 App.config 中的错误连接字符串或假定默认连接字符串(如 DbContext 的默认构造函数),它在生产中崩溃了做。我想在

  • 调试/发布(并且只注入(inject)一个不同的 IConnectionStringProvider )
  • 调用 Add-Migration脚本
  • 正在运行 DbMigrator.GetPendingMigrations()

目前我收到了其中一些消息:

The context factory type 'Test.MyContextFactory' does not have a public parameterless constructor. Either add a public parameterless constructor, create an IDbContextFactory implementation in the context assembly, or register a context factory using DbConfiguration.

---更新---

这可能是 How do I inject a connection string into an instance of IDbContextFactory<T>? 的副本但它没有解决办法。我解释一下原因:

  • 我总是使用 Add-Migration带有连接字符串,那么我如何提供 DbContextIDbContextFactory<>那会消耗它吗?而不是无参数构造函数?

    Add-Migration MyMigration -ConnectionStringName "MyConnectionString"

  • 同样的问题:我使用 DbMigrator.GetPendingMigrations()这也要求无参数 DbContextIDbContextFactory<>实现。

据我了解,EntityFramework 违反了封装 by implying default constructors和原因 temporal coupling这不是故障安全的。所以请提出一个没有无参数构造函数的解决方案。

最佳答案

I always use Add-Migration with connection string, so how can I provide a DbContext or IDbContextFactory<> that consumes it? Instead of parameterless constructors?

在花了一些时间对 Entity Framework 进行逆向工程后,结果证明答案是:你做不到!

这是运行 Add-Migration 时发生的情况(没有默认构造函数):

System.Data.Entity.Migrations.Infrastructure.MigrationsException: The target context 'Namespace.MyContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()

让我们看看 DbMigrator构造函数。当从 Add-Migration 运行时命令,usersContext为空,configuration.TargetDatabase null 并且包含从命令行参数传递的信息,例如-ConnectionStringName , -ConnectionString-ConnectionProviderName .所以new DbContextInfo(configuration.ContextType, configuration.TargetDatabase)被称为。

internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, bool calledByCreateDatabase) : base(null)
{
Check.NotNull(configuration, "configuration");
Check.NotNull(configuration.ContextType, "configuration.ContextType");
_configuration = configuration;
_calledByCreateDatabase = calledByCreateDatabase;
_existenceState = existenceState;
if (usersContext != null)
{
_usersContextInfo = new DbContextInfo(usersContext);
}
else
{
_usersContextInfo = ((configuration.TargetDatabase == null) ?
new DbContextInfo(configuration.ContextType) :
new DbContextInfo(configuration.ContextType, configuration.TargetDatabase));
if (!_usersContextInfo.IsConstructible)
{
throw Error.ContextNotConstructible(configuration.ContextType);
}
}
// ...
}

对于 DbMigrator不要扔,DbContextInfo实例必须是可构造的。现在,让我们看看 DbContextInfo构造函数。对于 DbContextInfo是可构造的,两者都是CreateActivator()CreateInstance()不得返回 null。

private DbContextInfo(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func<IDbDependencyResolver> resolver = null)
{
_resolver = (resolver ?? ((Func<IDbDependencyResolver>)(() => DbConfiguration.DependencyResolver)));
_contextType = contextType;
_modelProviderInfo = modelProviderInfo;
_appConfig = config;
_connectionInfo = connectionInfo;
_activator = CreateActivator();
if (_activator != null)
{
DbContext dbContext = CreateInstance();
if (dbContext != null)
{
_isConstructible = true;
using (dbContext)
{
_connectionString = DbInterception.Dispatch.Connection.GetConnectionString(dbContext.InternalContext.Connection, new DbInterceptionContext().WithDbContext(dbContext));
_connectionStringName = dbContext.InternalContext.ConnectionStringName;
_connectionProviderName = dbContext.InternalContext.ProviderName;
_connectionStringOrigin = dbContext.InternalContext.ConnectionStringOrigin;
}
}
}
public virtual bool IsConstructible => _isConstructible;
}

CreateActivator基本上搜索 DbContext 类型或 IDbContextFactory<MyContext> 的无参数构造函数执行并返回 Func<MyContext> .那么CreateInstance调用那个激活器。不幸的是,DbConnectionInfo connectionInfo DbContextInfo 的参数激活器不使用构造函数,但仅在创建上下文实例后才应用(为简洁起见,删除了不相关的代码):

public virtual DbContext CreateInstance()
{
dbContext = _activator == null ? null : _activator();
dbContext.InternalContext.ApplyContextInfo(this);
return dbContext;
}

然后,在ApplyContextInfo里面,奇迹发生了:连接信息(来自 _connectionInfo)在新创建的上下文中被覆盖。

因此,鉴于您必须有一个无参数的构造函数,我的解决方案与您的类似,但进行了一些更积极的检查。

  1. 默认构造函数仅在调试配置中编译时添加。
  2. 如果未从 Add-Migration 中调用,默认构造函数将抛出命令。

这是我的上下文:

public class MyContext : DbContext
{
static MyContext()
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MyContextConfiguration>(useSuppliedContext: true));
}

#if DEBUG
public MyContext()
{
var stackTrace = new System.Diagnostics.StackTrace();
var isMigration = stackTrace.GetFrames()?.Any(e => e.GetMethod().DeclaringType?.Namespace == typeof(System.Data.Entity.Migrations.Design.ToolingFacade).Namespace) ?? false;
if (!isMigration)
throw new InvalidOperationException($"The {GetType().Name} default constructor must be used exclusively for running Add-Migration in the Package Manager Console.");
}
#endif
// ...
}

那我终于可以跑了

Add-Migration -Verbose -ConnectionString "Server=myServer;Database=myDatabase;Integrated Security=SSPI" -ConnectionProviderName "System.Data.SqlClient"

对于运行迁移,我还没有找到使用 DbMigrator 的解决方案明确地,所以我使用 MigrateDatabaseToLatestVersion数据库初始化器 useSuppliedContext: trueHow do I inject a connection string into an instance of IDbContextFactory? 中所述.

关于c# - 没有无参数 DbContext 和 DbContextFactory 构造函数的添加迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42296196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com