问题描述
当我使用.netcore3.1向导20.1.3创建新的Dev Express XAF应用程序时,代码可以正常工作.我可以启用迁移并运行迁移而不会出现问题. (或者我以为...参见下文)
When I create a new Dev Express XAF application using the wizard 20.1.3 for .netcore3.1 the code works fine. I can enable migrations and run a migration without problems. (Or so I thought ... see below)
但是由于某些原因(我的旧调用run-migrations代码),我想向构造函数提供连接字符串的位置
However for certain reasons (my legacy call run-migrations code) I want to provide the connection string location to the constructor
当我这样做时,尝试添加一个偏头痛,我会收到一个错误消息
When I do this, and try to add a migratiion I get an error
DbContext设置为
The DbContext is set up as
using System;
using System.Data.Entity;
using System.Data.Common;
using DevExpress.ExpressApp.EF.Updating;
using DevExpress.Persistent.BaseImpl.EF;
using DevExpress.ExpressApp.Design;
using DevExpress.Persistent.BaseImpl.EF.PermissionPolicy;
namespace Creatures.Module.BusinessObjects {
[TypesInfoInitializer(typeof(CreaturesContextInitializer))]
public class CreaturesDbContext : DbContext {
public CreaturesDbContext(String connectionString)
: base(connectionString) {
}
public CreaturesDbContext(DbConnection connection)
: base(connection, false) {
}
// migrations work
public CreaturesDbContext()
{
}
// migratations do not work
//public CreaturesDbContext()
// : base("name=ConnectionString")
// {
//
// }
public DbSet<ModuleInfo> ModulesInfo { get; set; }
public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<PermissionPolicyTypePermissionObject> TypePermissionObjects { get; set; }
public DbSet<PermissionPolicyUser> Users { get; set; }
public DbSet<ModelDifference> ModelDifferences { get; set; }
public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
public DbSet<Cat> Cats { get; set; }
}
}
也有
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using DevExpress.ExpressApp.EF.DesignTime;
namespace Creatures.Module.BusinessObjects
{
public class CreaturesContextInitializer : DbContextTypesInfoInitializerBase {
protected override DbContext CreateDbContext() {
DbContextInfo contextInfo = new DbContextInfo(typeof(CreaturesDbContext), new DbProviderInfo(providerInvariantName: "System.Data.SqlClient", providerManifestToken: "2008"));
return contextInfo.CreateInstance();
}
}
}
我在Win项目app.config中拥有
In the win project app.config i have
<add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Server=myserver;Database=Creatures;Integrated Security=false;MultipleActiveResultSets=True;user=myuser;pwd=mypassword;" />
在PM Console上,我添加了迁移
At PM Console I add a migration
PM> add-migration migration-name
输出是
System.InvalidOperationException: No connection string named 'ConnectionString' could be found in the application config file.
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, Func`1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType)
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.Infrastructure.Design.Executor.CreateMigrationScaffolder(DbMigrationsConfiguration configuration)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
No connection string named 'ConnectionString' could be found in the application config file.
我还想知道构造函数在调用时不从基类继承的情况下如何知道"连接字符串的位置
I also wonder how the constructor "knows" the connection string location when it is called without inheriting from base
[更新]
我试图解决这个问题,但无法正常工作
I tried to make a work around but could not get it working
该资源可在 GitHub
我可以使用Package Manager Console在代码中创建迁移.但是,如果我尝试从PM更新数据库,它将使用错误的名称创建一个新数据库.
I can use Package Manager Console to create migrations in the code.But if I try to update the database from PM it creates a new database with the wrong name.
我的要点如下
public static void RunMigrations(Creatures3DbContext db)
{
var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
var pendings = migrator.GetPendingMigrations(); // gets the migrations if only if it is not told the db
var migratorwithDb = new DbMigrator(configuration, db); // runs the migrations only if it is told the db
foreach (var pending in pendings)
{
migratorwithDb.Update(pending); // appears to run but the application still has a model backing failure
}
}
[更新]
或者我想.当我重新调查时,事实证明迁移正在创建其他数据库.
Or so I thought. When I reinvestigated this it turns out that the migration is creating a different database.
这是PM输出的开始
PM> enable-migrations
Checking if the context targets an existing database...
PM> add-migration cat
Scaffolding migration 'cat'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration cat' again.
PM> update-database -verbose
C:\Program Files\dotnet\dotnet.exe exec --depsfile D:\Users\kirst\source\repos\Creatures6\Creatures6.Module\bin\Debug\netcoreapp3.0\Creatures6.Module.deps.json --additionalprobingpath C:\Users\kirst\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\Users\kirst\source\repos\Creatures6\Creatures6.Module\bin\Debug\netcoreapp3.0\Creatures6.Module.runtimeconfig.json C:\Users\kirst\.nuget\packages\entityframework\6.4.0\tools\netcoreapp3.0\any\ef6.dll database update --verbose --no-color --prefix-output --assembly D:\Users\kirst\source\repos\Creatures6\Creatures6.Module\bin\Debug\netcoreapp3.0\Creatures6.Module.dll --project-dir D:\Users\kirst\source\repos\Creatures6\Creatures6.Module\ --language C# --root-namespace Creatures6.Module --config D:\Users\kirst\source\repos\Creatures6\Creatures6.Win\App.config
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Creatures6.Module.BusinessObjects.Creatures6DbContext' (DataSource: (localdb)\mssqllocaldb, Provider: System.Data.SqlClient, Origin: Convention).
Applying explicit migrations: [202005150136061_cat].
Applying explicit migration: 202005150136061_cat.
CREATE TABLE [dbo].[ModelDifferenceAspects] (
[ID] [int] NOT NULL IDENTITY,
[Name] [nvarchar](max),
[Xml] [nvarchar](max),
[Owner_ID] [int],
CONSTRAINT [PK_dbo.ModelDifferenceAspects] PRIMARY KEY ([ID])
)
CREATE INDEX [IX_Owner_ID] ON [dbo].[ModelDifferenceAspects]([Owner_ID])
CREATE TABLE [dbo].[ModelDifferences] (
[ID] [int] NOT NULL IDENTITY,
[UserId] [nvarchar](max),
[ContextId] [nvarchar](max),
[Version] [int] NOT NULL,
CONSTRAINT [PK_dbo.ModelDifferences] PRIMARY KEY ([ID])
)
CREATE TABLE [dbo].[ModuleInfoes] (
[ID] [int] NOT NULL IDENTITY,
[Name] [nvarchar](max),
[Version] [nvarchar](max),
[AssemblyFileName] [nvarchar](max),
[IsMain] [bit] NOT NULL,
CONSTRAINT [PK_dbo.ModuleInfoes] PRIMARY KEY ([ID])
)
CREATE TABLE [dbo].[PermissionPolicyRoleBases] (
[ID] [int] NOT NULL IDENTITY,
[Name] [nvarchar](max),
[IsAdministrative] [bit] NOT NULL,
[CanEditModel] [bit] NOT NULL,
[PermissionPolicy] [int] NOT NULL,
[IsAllowPermissionPriority] [bit] NOT NULL,
[Discriminator] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.PermissionPolicyRoleBases] PRIMARY KEY ([ID])
)
CREATE TABLE [dbo].[PermissionPolicyActionPermissionObjects] (
[ID] [int] NOT NULL IDENTITY,
[ActionId] [nvarchar](max),
[Role_ID] [int],
CONSTRAINT [PK_dbo.PermissionPolicyActionPermissionObjects] PRIMARY KEY ([ID])
)
CREATE INDEX [IX_Role_ID] ON [dbo].[PermissionPolicyActionPermissionObjects]([Role_ID])
CREATE TABLE [dbo].[PermissionPolicyNavigationPermissionObjects] (
[ID] [int] NOT NULL IDENTITY,
[ItemPath] [nvarchar](max),
[TargetTypeFullName] [nvarchar](max),
[NavigateState] [int],
[Role_ID] [int],
CONSTRAINT [PK_dbo.PermissionPolicyNavigationPermissionObjects] PRIMARY KEY ([ID])
)
CREATE INDEX [IX_Role_ID] ON [dbo].[PermissionPolicyNavigationPermissionObjects]([Role_ID])
CREATE TABLE [dbo].[PermissionPolicyTypePermissionObjects] (
[ID] [int] NOT NULL IDENTITY,
[TargetTypeFullName] [nvarchar](max),
[ReadState] [int],
[WriteState] [int],
[CreateState] [int],
[DeleteState] [int],
[NavigateState] [int],
[Role_ID] [int],
CONSTRAINT [PK_dbo.PermissionPolicyTypePermissionObjects] PRIMARY KEY ([ID])
)
CREATE INDEX [IX_Role_ID] ON [dbo].[PermissionPolicyTypePermissionObjects]([Role_ID])
CREATE TABLE [dbo].[PermissionPolicyMemberPermissionsObjects] (
[ID] [int] NOT NULL IDENTITY,
[Members] [nvarchar](max),
[Criteria] [nvarchar](max),
[ReadState] [int],
[WriteState] [int],
[TypePermissionObject_ID] [int],
CONSTRAINT [PK_dbo.PermissionPolicyMemberPermissionsObjects] PRIMARY KEY ([ID])
)
CREATE INDEX [IX_TypePermissionObject_ID] ON [dbo].[PermissionPolicyMemberPermissionsObjects]([TypePermissionObject_ID])
CREATE TABLE [dbo].[PermissionPolicyObjectPermissionsObjects] (
[ID] [int] NOT NULL IDENTITY,
[Criteria] [nvarchar](max),
[ReadState] [int],
[WriteState] [int],
[DeleteState] [int],
[NavigateState] [int],
[TypePermissionObject_ID] [int],
CONSTRAINT [PK_dbo.PermissionPolicyObjectPermissionsObjects] PRIMARY KEY ([ID])
)
CREATE INDEX [IX_TypePermissionObject_ID] ON [dbo].[PermissionPolicyObjectPermissionsObjects]([TypePermissionObject_ID])
CREATE TABLE [dbo].[PermissionPolicyUsers] (
[ID] [int] NOT NULL IDENTITY,
[UserName] [nvarchar](max),
[IsActive] [bit] NOT NULL,
[ChangePasswordOnFirstLogon] [bit] NOT NULL,
[StoredPassword] [nvarchar](max),
CONSTRAINT [PK_dbo.PermissionPolicyUsers] PRIMARY KEY ([ID])
)
CREATE TABLE [dbo].[PermissionPolicyUserPermissionPolicyRoles] (
[PermissionPolicyUser_ID] [int] NOT NULL,
[PermissionPolicyRole_ID] [int] NOT NULL,
CONSTRAINT [PK_dbo.PermissionPolicyUserPermissionPolicyRoles] PRIMARY KEY ([PermissionPolicyUser_ID], [PermissionPolicyRole_ID])
)
CREATE INDEX [IX_PermissionPolicyUser_ID] ON [dbo].[PermissionPolicyUserPermissionPolicyRoles]([PermissionPolicyUser_ID])
CREATE INDEX [IX_PermissionPolicyRole_ID] ON [dbo].[PermissionPolicyUserPermissionPolicyRoles]([PermissionPolicyRole_ID])
ALTER TABLE [dbo].[ModelDifferenceAspects] ADD CONSTRAINT [FK_dbo.ModelDifferenceAspects_dbo.ModelDifferences_Owner_ID] FOREIGN KEY ([Owner_ID]) REFERENCES [dbo].[ModelDifferences] ([ID])
ALTER TABLE [dbo].[PermissionPolicyActionPermissionObjects] ADD CONSTRAINT [FK_dbo.PermissionPolicyActionPermissionObjects_dbo.PermissionPolicyRoleBases_Role_ID] FOREIGN KEY ([Role_ID]) REFERENCES [dbo].[PermissionPolicyRoleBases] ([ID])
ALTER TABLE [dbo].[PermissionPolicyNavigationPermissionObjects] ADD CONSTRAINT [FK_dbo.PermissionPolicyNavigationPermissionObjects_dbo.PermissionPolicyRoleBases_Role_ID] FOREIGN KEY ([Role_ID]) REFERENCES [dbo].[PermissionPolicyRoleBases] ([ID])
ALTER TABLE [dbo].[PermissionPolicyTypePermissionObjects] ADD CONSTRAINT [FK_dbo.PermissionPolicyTypePermissionObjects_dbo.PermissionPolicyRoleBases_Role_ID] FOREIGN KEY ([Role_ID]) REFERENCES [dbo].[PermissionPolicyRoleBases] ([ID])
ALTER TABLE [dbo].[PermissionPolicyMemberPermissionsObjects] ADD CONSTRAINT [FK_dbo.PermissionPolicyMemberPermissionsObjects_dbo.PermissionPolicyTypePermissionObjects_TypePermissionObject_ID] FOREIGN KEY ([TypePermissionObject_ID]) REFERENCES [dbo].[PermissionPolicyTypePermissionObjects] ([ID])
ALTER TABLE [dbo].[PermissionPolicyObjectPermissionsObjects] ADD CONSTRAINT [FK_dbo.PermissionPolicyObjectPermissionsObjects_dbo.PermissionPolicyTypePermissionObjects_TypePermissionObject_ID] FOREIGN KEY ([TypePermissionObject_ID]) REFERENCES [dbo].[PermissionPolicyTypePermissionObjects] ([ID])
ALTER TABLE [dbo].[PermissionPolicyUserPermissionPolicyRoles] ADD CONSTRAINT [FK_dbo.PermissionPolicyUserPermissionPolicyRoles_dbo.PermissionPolicyUsers_PermissionPolicyUser_ID] FOREIGN KEY ([PermissionPolicyUser_ID]) REFERENCES [dbo].[PermissionPolicyUsers] ([ID]) ON DELETE CASCADE
ALTER TABLE [dbo].[PermissionPolicyUserPermissionPolicyRoles] ADD CONSTRAINT [FK_dbo.PermissionPolicyUserPermissionPolicyRoles_dbo.PermissionPolicyRoleBases_PermissionPolicyRole_ID] FOREIGN KEY ([PermissionPolicyRole_ID]) REFERENCES [dbo].[PermissionPolicyRoleBases] ([ID]) ON DELETE CASCADE
CREATE TABLE [dbo].[__MigrationHistory] (
[MigrationId] [nvarchar](150) NOT NULL,
[ContextKey] [nvarchar](300) NOT NULL,
[Model] [varbinary](max) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])
)
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'202005150136061_cat', N'Creatures6.Module.Migrations.Configuration', etc
[更新]
我尝试为20.1.3 Framework和19.2 Framework创建一些新的xaf项目当我尝试从Package Manager控制台运行Update-Database -verbose时,它们都在定位数据库时遇到问题.显示输出
I tried making some new xaf projects for 20.1.3 Framework and 19.2 FrameworkThey both had issues locating the database when I try to run Update-Database -verbose from Package Manager Console. The output indicated
Target database is: 'creatures9.Module.BusinessObjects.creatures9DbContext' (DataSource: .\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Convention).
我正在运行VS2019 16.5.4
I am running VS2019 16.5.4
app.config中的连接字符串未提及SQLExpress,数据库名称为生物9
The connection string in app.config does not mention SQLExpress and the database name is creatures9
我认为问题不在于实体框架本身,因为XAF 19.2使用EF 6.2
I don't think the problem is Entity Framwork itself because XAF 19.2 use EF 6.2
我现在正在考虑在Nuget中进行某些操作.我刚刚更新到VS 2019 16.5.5,但没有帮助.
I am now thinking something in Nuget maybe.I just updated to VS 2019 16.5.5 but it did not help.
[更新]
[更新]
启用迁移后,也许我需要指定连接字符串的位置
Maybe I need to specify the location of the connection string when I enable migrations
我尝试过
enable-migrations -StartupProjectName Creatures3.Win -ConnectionStringName ConnectionString
但是随信附上
No connection string named 'ConnectionString' could be found in the application config file.
好像我用
update-database
不指定连接字符串的位置,那么它将使用上下文的全名创建和更新数据库
without specifying the connectionstring location then it creates and updates a database with the full name of the context
我希望它使用连接字符串中指定的数据库,所以我尝试了
I want it to use the database specified in the connection string so I tried
update-database -verbose -StartupProjectName Creatures3.Win -ConnectionStringName ConnectionString
输出如下
C:\Program Files\dotnet\dotnet.exe exec --depsfile D:\Users\kirst\source\repos\Creatures3\Creatures3.Module\bin\Debug\netcoreapp3.0\Creatures3.Module.deps.json --additionalprobingpath C:\Users\kirst\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\Users\kirst\source\repos\Creatures3\Creatures3.Module\bin\Debug\netcoreapp3.0\Creatures3.Module.runtimeconfig.json C:\Users\kirst\.nuget\packages\entityframework\6.4.0\tools\netcoreapp3.0\any\ef6.dll database update --connection-string-name ConnectionString --verbose --no-color --prefix-output --assembly D:\Users\kirst\source\repos\Creatures3\Creatures3.Module\bin\Debug\netcoreapp3.0\Creatures3.Module.dll --project-dir D:\Users\kirst\source\repos\Creatures3\Creatures3.Module\ --language C# --root-namespace Creatures3.Module --config D:\Users\kirst\source\repos\Creatures3\Creatures3.Win\App.config
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.InvalidOperationException: No connection string named 'ConnectionString' could be found in the application config file.
at System.Data.Entity.Infrastructure.DbConnectionInfo.GetConnectionString(AppConfig config)
at System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
at System.Data.Entity.Internal.LazyInternalContext.OverrideConnection(IInternalConnection connection)
at System.Data.Entity.Infrastructure.DbContextInfo.ConfigureContext(DbContext context)
at System.Data.Entity.Internal.InternalContext.ApplyContextInfo(DbContextInfo info)
at System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbConnectionInfo connectionInfo)
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.Infrastructure.Design.Executor.CreateMigrator(DbMigrationsConfiguration configuration)
at System.Data.Entity.Infrastructure.Design.Executor.UpdateInternal(String targetMigration, Boolean force, DbConnectionInfo connectionInfo, String migrationsConfigurationName)
at System.Data.Entity.Infrastructure.Design.Executor.Update.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
No connection string named 'ConnectionString' could be found in the application config file.
按照这个疯狂的程序,我可以解决问题
I thing can work around things by following this crazy procedure
从XAF向导创建初始程序后,运行该程序以创建数据库.
After creating the initial program from the XAF Wizard run the program to create the database.
然后启用迁移
然后添加一个迁移
然后更新数据库
然后添加代码以在项目中运行迁移.并注释掉初始代码以创建要迁移的表
Then add the code to run migrations in the project.and comment out the intial code to create tables in migration one
然后运行项目
然后为每个新迁移使用add-migration创建它
Then for each new migration create it using add-migration
运行update-database更新不正确的数据库
Run update-database to update the incorrect database created
运行代码本身以更新正确的数据库.
Run the code itself to update the correct database.
添加迁移时,我尝试指定连接字符串的位置
I tried specifying the connection string location when adding the migration
PM> add-migration one -StartupProjectName Creatures3.Win -ConnectionStringName ConnectionString
但是我知道了
System.InvalidOperationException: No connection string named 'ConnectionString' could be found in the application config file.
at System.Data.Entity.Infrastructure.DbConnectionInfo.GetConnectionString(AppConfig config)
at System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
at System.Data.Entity.Internal.LazyInternalContext.OverrideConnection(IInternalConnection connection)
at System.Data.Entity.Infrastructure.DbContextInfo.ConfigureContext(DbContext context)
at System.Data.Entity.Internal.InternalContext.ApplyContextInfo(DbContextInfo info)
at System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbConnectionInfo connectionInfo)
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.Infrastructure.Design.Executor.CreateMigrationScaffolder(DbMigrationsConfiguration configuration)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
No connection string named 'ConnectionString' could be found in the application config file.
[更新]
我在调用update-database时尝试使用连接字符串本身
I tried the using the connection string itself when calling update-database
update-database -connectionString "Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Creatures3F"
它要求我提供连接提供商的名称
It asked me for the connection provider name
因此输入
"System.Data.SqlClient"
"System.Data.SqlClient"
所以看来以下是解决方法
So it seems thatthe following is a work around
update-database -connectionString "Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Creatures3" -ConnectionProviderName "System.Data.SqlClient" -verbose
[更新]
我尝试了Kahbazi的建议,但创建迁移时出错.
I tried Kahbazi's suggestion but there is an error creating the migration.
PM> add-migration E
给予
System.InvalidOperationException: No connection string named 'ConnectionString' could be found in the application config file.
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, Func`1 resolver)
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType)
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.Infrastructure.Design.Executor.CreateMigrationScaffolder(DbMigrationsConfiguration configuration)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
No connection string named 'ConnectionString' could be found in the application config file.
[更新]
我尝试了Kahbazi的建议使用CreaturesDbContextFactory
I tried Kahbazi's suggestion to use CreaturesDbContextFactory
但是
update-database -vebose
将目标数据库显示为'Creatures3.Module.BusinessObjects.Creatures3DbContext'
shows target database as 'Creatures3.Module.BusinessObjects.Creatures3DbContext'
推荐答案
您可以实现IDbContextFactory
并在其中硬编码连接字符串,以便migrations命令可以使用它.
You can implement IDbContextFactory
and hardcode your connection string in it, so the migrations command could use it.
public class CreaturesDbContextFactory : IDbContextFactory<CreaturesDbContext>
{
public CreaturesDbContext Create()
{
return new CreaturesDbContext("Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Creatures3");
}
}
在DbContext
中,您还必须具有一个采用连接字符串的构造函数.
Also in your DbContext
you must have a constructor which takes connection string.
public CreaturesDbContext(string connectionString)
: base(connectionString)
{
...
}
这篇关于在应用程序配置文件(EF无参数构造函数)中找不到名为"ConnectionString"的连接字符串.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!