No connection string named 'ConnectionString' could be found in the application config file (EF parameterless constructor )

天涯浪子 提交于 2020-06-17 00:49:31

问题


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)

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

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; }
    }
}

Also there is

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();
        }
    }
}

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;" />

At PM Console I add a migration

PM> add-migration migration-name

output is

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

[Update]

I tried to make a work around but could not get it working

The source is available on GitHub

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.

The gist of my hack is the following

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
       }
   }

[Update]

I can enable migrations and run a migration without problems.

Or so I thought. When I reinvestigated this it turns out that the migration is creating a different database.

Here is the start of the output from 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

[Update]

I tried making some new xaf projects for 20.1.3 Framework and 19.2 Framework They 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).

I am running VS2019 16.5.4

The connection string in app.config does not mention SQLExpress and the database name is creatures9

I don't think the problem is Entity Framwork itself because XAF 19.2 use EF 6.2

I am now thinking something in Nuget maybe. I just updated to VS 2019 16.5.5 but it did not help.

[Update]

[Update]

Maybe I need to specify the location of the connection string when I enable migrations

I tried

enable-migrations -StartupProjectName Creatures3.Win -ConnectionStringName ConnectionString 

However that comes up with a message

No connection string named 'ConnectionString' could be found in the application config file.

It seems that if I use

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 

The output was as follows

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

After creating the initial program from the XAF Wizard run the program to create the database.

Then enable-migrations

Then add-migration one

Then update-database

Then add the code to run migrations in the project. and comment out the intial code to create tables in migration one

Then run the project

Then for each new migration create it using add-migration

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 

But I got

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]

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

so typed in

"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

[Update]

I tried Kahbazi's suggestion but there is an error creating the migration.

 PM> add-migration E

gives

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.

[Update]

I tried Kahbazi's suggestion to use CreaturesDbContextFactory

but

 update-database -vebose 

shows target database as 'Creatures3.Module.BusinessObjects.Creatures3DbContext'


回答1:


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");
    }
}

Also in your DbContext you must have a constructor which takes connection string.

public CreaturesDbContext(string connectionString)
    : base(connectionString)
{
    ...       
}



回答2:


Let's say you have this constructor

public CreaturesDbContext()
    : base("name=MyDatabaseConnectionString")
{
    ...       
}

When you are running update-database command, it will look into your app.config or web.config (based on what type of project your DbContext exists in) and look for a connection string with the name of MyDatabaseConnectionString.

The error you are getting is simply because there is no connection string with the name of MyDatabaseConnectionString in your app.config/web.config.

Add this in your app.config/web.config to fix this issue, so you don't need to send the connection string with updata-databse command everytime.

<configuration>
  <connectionStrings>
    <add name="MyDatabaseConnectionString" connectionString="Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Creatures3" />
  </connectionStrings>
</configuration>  



回答3:


It seems that this is a bug in EF6.4 with DotNetCore and the work around is to provide the connection string etc to the update-database command as at the end of my question.




回答4:


I've started to get this issue when I switched my data project to from .NET4.7 to .NET Core 3.1 framework.

So in my .csproj I've replaced

<TargetFramework>netcoreapp3.1</TargetFramework>

By

<TargetFrameworks>net47;netcoreapp3.1</TargetFrameworks>

The the migration commands restarted to work properly. The downside is it's now a multi framework project :)

I've also noticed the order of the frameworks is important ("netcoreapp3.1;net47" failed)

Note: I'm also using EF version 6.4



来源:https://stackoverflow.com/questions/61786767/no-connection-string-named-connectionstring-could-be-found-in-the-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!