问:
No connection string named 'ConnectionString' could be found in the application config file (EF parameterless constructor )
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

```<code>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; }
    }
}
</code>```

Also there is

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

In the win project app.config i have

```<code>  <add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Server=myserver;Database=Creatures;Integrated Security=false;MultipleActiveResultSets=True;user=myuser;pwd=mypassword;" />
</code>```

At PM Console I add a migration

```<code>PM> add-migration migration-name
</code>```

output is

```<code>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.
</code>```

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

```<code>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
       }
   }
</code>```

[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

```<code>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
</code>```

[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

```<code>Target database is: 'creatures9.Module.BusinessObjects.creatures9DbContext' (DataSource: .\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Convention).
</code>```

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

```<code>enable-migrations -StartupProjectName Creatures3.Win -ConnectionStringName ConnectionString
</code>```

However that comes up with a message

```<code>No connection string named 'ConnectionString' could be found in the application config file.
</code>```

It seems that if I use

```<code>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();
        }
    }
}
</code>```0

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

```<code>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();
        }
    }
}
</code>```1

The output was as follows

```<code>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();
        }
    }
}
</code>```2

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

```<code>PM> add-migration one -StartupProjectName Creatures3.Win -ConnectionStringName ConnectionString
</code>```

But I got

```<code>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.
</code>```

[Update]

I tried the using the connection string itself when calling update-database

```<code>update-database -connectionString   "Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Creatures3F"
</code>```

It asked me for the connection provider name

so typed in

"System.Data.SqlClient"

So it seems thatthe following is a work around

```<code>update-database -connectionString   "Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=Creatures3" -ConnectionProviderName "System.Data.SqlClient" -verbose
</code>```

[Update]

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

```<code> PM> add-migration E
</code>```

gives

```<code>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.
</code>```

[Update]

I tried Kahbazi's suggestion to use CreaturesDbContextFactory

but

```<code> update-database -vebose
</code>```

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

答:
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

```<code><TargetFramework>netcoreapp3.1</TargetFramework>
</code>```

By

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

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

Body:
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'

Body:
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


来源: stackexchange

问:
Unable to fetch data from webservice with Retrofit
I'm trying to load some very simple data in JSON format, generated by a webservice, using Retrofit and Gson and also trying to implement MVVM architecture, but I'm getting a null value when calling data from  ViewModel:
I've seen many SO questions (or maybe not so many) but can't figure out where and why I'm getting this problems.

So, what I have is this

JSON RESPONSE: This could be either this one:

```<code>{
    "ok": [
        {
            "id": 1,
            "username": "test1",
            "pass": "123",
            "reg_date": "2020-05-20 00:00:00"
        }
    ]
}
</code>```

or this:

```<code>{
    "error": [
        {
            "message":"user doesn't exists"
        }
    ]
}
</code>```

I've created the correspondign POJOs for each response type, which I'll omit for simplicity. But also I've created a generic POJO for handling the response (thanks to @Công Hải, )

**POJOGenericResponse.java*

```<code>public class POJOGenericResponse{
    @SerializedName("ok")
    private LiveData<ArrayList<POJOUsr>> user;
    @SerializedName("error")
    private LiveData<ArrayList<POJOError>> error;

    //Constructor and Getters...
}
</code>```

JsonApi.java

```<code>public interface JsonApi {
    @GET("SelectAllUsr.php")
    Call<LiveData<POJOGenericResponse>> getGenericResponse();
}
</code>```

I don't know how this class should be called, according to its purpose and name conventions

RetrofitInstance.java

```<code>public class RetrofitInstance {
    private static String URL_BASE = "http://192.168.0.35/app_android/webservices/";
    private static Retrofit retrofit;
    private static Gson gson;

    public Retrofit getRetrofitInstance(){
        gson = new GsonBuilder().setLenient().create();
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL_BASE)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }
}
</code>```

LoginRepository.java

```<code>public class LoginRepository{
    private RetrofitInstance retrofitInstance;
    private JsonApi jsonApi;
    private LiveData<POJOGenericResponse> genericResponse;
    private Call<LiveData<POJOGenericResponse>> call;

    public LoginRepository() {
        retrofitInstance = new RetrofitInstance();
        jsonApi = retrofitInstance.getRetrofitInstance().create(JsonApi.class);
        call = jsonApi.getRespuestaGenerica();
    }

    //TODO: This should be done in another class??
    public LiveData<POJOGenericResponse> getGenericResponse() {
        call.clone().enqueue(new Callback<LiveData<POJOGenericResponse>>() {

            @Override
            public void onResponse(Call<LiveData<POJOGenericResponse>> call, Response<LiveData<POJOGenericResponse>> response) {
                if (response.isSuccessful()) {
                    genericResponse= response.body();
                } else {
                    //
                }
            }

            @Override
            public void onFailure(Call<LiveData<POJOGenericResponse>> call, Throwable t) {
                //
            }
        });
        return genericResponse;
    }
}
</code>```

LoginViewModel.java

```<code>public class LoginViewModel extends AndroidViewModel {
    private RepositorioLogin loginRepository;
    private MutableLiveData<POJOGenericResponse> serverResponse;

    public ViewModelLogin(@NonNull Application application) {
        super(application);
        loginRepository = new RepositorioLogin();
        serverResponse = new MutableLiveData<>();
    }

    public void setServerResponse(){
        serverResponse.setValue(loginRepository.getGenericResponse().getValue());
    }

    public LiveData<POJORespuestaGenerica> getServerResponse(){
        return serverResponse;
    }
}
</code>```

Here's where the data should be shown

FragmentData.java

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_data, container, false);
        TextView exampleText = v.findViewById(R.id.tv_test);

        LoginViewModel loginViewModel = new ViewModelProvider(requireActivity()).get(LoginViewModel.class);
        loginViewModel.getServerResponse().observe(requireActivity(), new Observer<POJORespuestaGenerica>() {
            @Override
            public void onChanged(POJOGenericResponse pojoGenericResponse) {
                if (pojoGenericResponse.getUser() != null) {
                    exampleText.setText(pojoGenericResponse.getUser().getValue().get(0).getUsername());
                }
                if (pojoGenericResponse.getError() != null) {
                    exampleText.setText(pojoGenericResponse.getError().getValue().get(0).getMensaje());
                }
            }
        });
</code>```

When debugging, the error that I get is

response = Cannot find local variable 'response'         serverResponse.setValue(loginRepository.getGenericResponse().getValue());\n = java.lang.NullPointerException
  response = Cannot find local variable 'response'

which describe the problem by itself, but can't manage to solve it.

Also, any recommendation on the implementation of the MVVM architecture will be very appreciated.

Beforehand, thank you very much

答:
Looks like this is an incorrect bit --

```<code>public LiveData<POJOGenericResponse> getGenericResponse() {
        call.clone().enqueue(new Callback<LiveData<POJOGenericResponse>>() {

            @Override
            public void onResponse(Call<LiveData<POJOGenericResponse>> call, Response<LiveData<POJOGenericResponse>> response) {
                if (response.isSuccessful()) {
                    genericResponse= response.body();
                } else {
                    //
                }
            }

            @Override
            public void onFailure(Call<LiveData<POJOGenericResponse>> call, Throwable t) {
                //
            }
        });
        return genericResponse;
    }
</code>```

So onResponse is an asynchronous call and you are returning the return genericResponse; immediately from the method.

Rather than getting a return from this method change it to void and directly observe on private LiveData<POJOGenericResponse> genericResponse;

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to load some very simple data in JSON format, generated by a webservice, using Retrofit and Gson and also trying to implement MVVM architecture, but I'm getting a null value when calling data from  ViewModel:
I've seen many SO questions (or maybe not so many) but can't figure out where and why I'm getting this problems.

So, what I have is this

JSON RESPONSE: This could be either this one:

{
    "ok": [
        {
            "id": 1,
            "username": "test1",
            "pass": "123",
            "reg_date": "2020-05-20 00:00:00"
        }
    ]
}

or this:

{
    "error": [
        {
            "message":"user doesn't exists"
        }
    ]
}

I've created the correspondign POJOs for each response type, which I'll omit for simplicity. But also I've created a generic POJO for handling the response (thanks to @Công Hải, )

**POJOGenericResponse.java*

public class POJOGenericResponse{
    @SerializedName("ok")
    private LiveData<ArrayList<POJOUsr>> user;
    @SerializedName("error")
    private LiveData<ArrayList<POJOError>> error;

    //Constructor and Getters...
}

JsonApi.java

public interface JsonApi {
    @GET("SelectAllUsr.php")
    Call<LiveData<POJOGenericResponse>> getGenericResponse();
}

I don't know how this class should be called, according to its purpose and name conventions

RetrofitInstance.java

public class RetrofitInstance {
    private static String URL_BASE = "http://192.168.0.35/app_android/webservices/";
    private static Retrofit retrofit;
    private static Gson gson;

    public Retrofit getRetrofitInstance(){
        gson = new GsonBuilder().setLenient().create();
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL_BASE)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }
}

LoginRepository.java

public class LoginRepository{
    private RetrofitInstance retrofitInstance;
    private JsonApi jsonApi;
    private LiveData<POJOGenericResponse> genericResponse;
    private Call<LiveData<POJOGenericResponse>> call;

    public LoginRepository() {
        retrofitInstance = new RetrofitInstance();
        jsonApi = retrofitInstance.getRetrofitInstance().create(JsonApi.class);
        call = jsonApi.getRespuestaGenerica();
    }

    //TODO: This should be done in another class??
    public LiveData<POJOGenericResponse> getGenericResponse() {
        call.clone().enqueue(new Callback<LiveData<POJOGenericResponse>>() {

            @Override
            public void onResponse(Call<LiveData<POJOGenericResponse>> call, Response<LiveData<POJOGenericResponse>> response) {
                if (response.isSuccessful()) {
                    genericResponse= response.body();
                } else {
                    //
                }
            }

            @Override
            public void onFailure(Call<LiveData<POJOGenericResponse>> call, Throwable t) {
                //
            }
        });
        return genericResponse;
    }
}

LoginViewModel.java

public class LoginViewModel extends AndroidViewModel {
    private RepositorioLogin loginRepository;
    private MutableLiveData<POJOGenericResponse> serverResponse;

    public ViewModelLogin(@NonNull Application application) {
        super(application);
        loginRepository = new RepositorioLogin();
        serverResponse = new MutableLiveData<>();
    }

    public void setServerResponse(){
        serverResponse.setValue(loginRepository.getGenericResponse().getValue());
    }

    public LiveData<POJORespuestaGenerica> getServerResponse(){
        return serverResponse;
    }
}

Here's where the data should be shown

FragmentData.java

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_data, container, false);
        TextView exampleText = v.findViewById(R.id.tv_test);

        LoginViewModel loginViewModel = new ViewModelProvider(requireActivity()).get(LoginViewModel.class);
        loginViewModel.getServerResponse().observe(requireActivity(), new Observer<POJORespuestaGenerica>() {
            @Override
            public void onChanged(POJOGenericResponse pojoGenericResponse) {
                if (pojoGenericResponse.getUser() != null) {
                    exampleText.setText(pojoGenericResponse.getUser().getValue().get(0).getUsername());
                }
                if (pojoGenericResponse.getError() != null) {
                    exampleText.setText(pojoGenericResponse.getError().getValue().get(0).getMensaje());
                }
            }
        });

When debugging, the error that I get is

response = Cannot find local variable 'response'         serverResponse.setValue(loginRepository.getGenericResponse().getValue());\n = java.lang.NullPointerException
  response = Cannot find local variable 'response'

which describe the problem by itself, but can't manage to solve it.

Also, any recommendation on the implementation of the MVVM architecture will be very appreciated.

Beforehand, thank you very much

Body:
Looks like this is an incorrect bit --

public LiveData<POJOGenericResponse> getGenericResponse() {
        call.clone().enqueue(new Callback<LiveData<POJOGenericResponse>>() {

            @Override
            public void onResponse(Call<LiveData<POJOGenericResponse>> call, Response<LiveData<POJOGenericResponse>> response) {
                if (response.isSuccessful()) {
                    genericResponse= response.body();
                } else {
                    //
                }
            }

            @Override
            public void onFailure(Call<LiveData<POJOGenericResponse>> call, Throwable t) {
                //
            }
        });
        return genericResponse;
    }

So onResponse is an asynchronous call and you are returning the return genericResponse; immediately from the method.

Rather than getting a return from this method change it to void and directly observe on private LiveData<POJOGenericResponse> genericResponse;


问:
How to insert an element at the last position in an array dynamically in C?
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

```<code>temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
</code>```

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

```<code>void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}
</code>```

Current output:

```<code>exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens
</code>```

Desired output:

```<code>tmp[5] = {1, 2, 5, 6, 8}
</code>```

答:
C does not have dynamic arrays. Arrays have a fixed size determined from their definition. You can allocate objects with malloc() that behave as arrays, but you must keep track of their allocated size separately. Appending an element requires reallocating the array so its address in memory may change.

In your code, tmp has a fixed size of 5 elements. You could maintain an index specifying how many elements are used and update that in the push function:

#include <stdio.h>

int push(int arr[], int value, size_t size, size_t *current) {
    if (*current < size) {
        arr[(*current)++] = value;
        return 0;
    } else {
        /* array is full */
        return -1;
    }
}

int main(void) {
    int temp[10] = { 1, 2, 0, 0, 5, 6, 0, 8, 0, 0 };
    int tmp[5];
    size_t pos = 0;

    for (size_t i = 0; i < sizeof(temp) / sizeof(temp[0]); i++) {
        if (temp[i])
            push(tmp, temp[i], sizeof(tmp) / sizeof(tmp[0]), &pos);
    }

    printf("tmp:");
    for (size_t i = 0; i < pos; i++) {
        printf(" %d", tmp[i]);
    }
    printf("\n");
    return 0;
}
```

Body:
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}

Current output:

exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens

Desired output:

tmp[5] = {1, 2, 5, 6, 8}


问:
Issue using React Hooks
I am getting this error while attempting to use useState within react:

https://i.imgur.com/XLQ7oq7.png

I have:

Reinstalled all modules

Made sure they are all up to date

Checked that I dont have duplicate react

I have thoroughly gone through this website and nothing helps

答:
As the error message says, "Hooks can only be called inside the body of a function component," but you have a class component. You need to first use a function component rather than a class component, and then make sure you are calling useState from the top level of the component, not from another function inside of it.

The React documentation includes this exact scenario as an example of why you would get this error:

Title: Issue using React Hooks


问:
How do you check if string ends with another string in Ada?
There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

```<code>declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end
</code>```

My intent is to establish a standard answer for Ada.

答:
A slight simplification of Simon's answer:</p>

```<code>function Ends_With (Source, Pattern : String) return Boolean is
begin
   return Pattern'Length <= Source'Length
     and then Source (Source'Last - Pattern'Length + 1 .. Source'Last) = Pattern;
end Ends_With;
</code>```

Body:
There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end

My intent is to establish a standard answer for Ada.

Body:
A slight simplification of Simon's answer:

function Ends_With (Source, Pattern : String) return Boolean is
begin
   return Pattern'Length <= Source'Length
     and then Source (Source'Last - Pattern'Length + 1 .. Source'Last) = Pattern;
end Ends_With;


问:
Angular testing - Testing interdependent services
I am new to the testing world, so sorry if this question is too obvious!

I have a fully functional and complex angular 9 project. I will explain my problem in simple terms here:

I have multiple services:

Service_MAIN (uses HttpClient, Router, etc.)

Service_A (uses Service_MAIN)

Service_B (uses Service_MAIN, and etc.)

Now I have successfully tested the Service_MAIN by creating spies, etc.

```<code>  let service: Service_MAIN;

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'put', 'post', 'delete', 'patch']);
    routerSpy = jasmine.createSpyObj('Router', ['navigate']);

    TestBed.configureTestingModule({
      imports: [MatSnackBarModule],
      providers: [
        Service_MAIN,
        {provide: HttpClient, useValue: httpClientSpy},
        {provide: Router, useValue: routerSpy},
        SnackBarService
      ]
    });
    service= TestBed.inject(Service_MAIN);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
  ...
  ...
</code>```

Now when I want to test Service_A and Service_B, do I again need to create a spy for my Service_MAIN and pass httpClientspy, routerSpy, etc.?

Also, if I once create a spy for Service_MAIN in order to test Service_A, do I need to create the same spy for Service_B as well?

It would create a lot of repetition in my test files.

NOTE: Service_A does not directly use HTTPCLIENT, it uses the Service_MAIN to make HTTP calls indirectly.

答:
When testing Service_A or Service_B, you can create a spyObj for Service_MAIN and mock the public methods of it that Service_A or Service_B depends on.

An example for testing Service_A.

```<code>let service: Service_A;
let mockServiceMain: any

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('serviceMain', [/* Put the public methods of serviceMain here as comma separated strings*/]);

    TestBed.configureTestingModule({
      imports: [],
      providers: [
        // Inject the actual service because it is to be tested
        Service_A,
        // when the service requests for Service_MAIN, use the mock value
        { provide: Service_MAIN, useValue: mockServiceMain },
        // your other providers or mock providers can go here
      ]
    });
    service = TestBed.inject(Service_A);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
</code>```

Also for the router, you should import RouterTestingModule and not stub it (https://angular.io/api/router/testing/RouterTestingModule). Same thing goes for HTTP, you should use HttpTestingController (https://angular.io/api/common/http/testing/HttpTestingController).

Body:
I am new to the testing world, so sorry if this question is too obvious!

I have a fully functional and complex angular 9 project. I will explain my problem in simple terms here:

I have multiple services:

Service_MAIN (uses HttpClient, Router, etc.)

Service_A (uses Service_MAIN)

Service_B (uses Service_MAIN, and etc.)

Now I have successfully tested the Service_MAIN by creating spies, etc.

  let service: Service_MAIN;

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'put', 'post', 'delete', 'patch']);
    routerSpy = jasmine.createSpyObj('Router', ['navigate']);

    TestBed.configureTestingModule({
      imports: [MatSnackBarModule],
      providers: [
        Service_MAIN,
        {provide: HttpClient, useValue: httpClientSpy},
        {provide: Router, useValue: routerSpy},
        SnackBarService
      ]
    });
    service= TestBed.inject(Service_MAIN);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
  ...
  ...

Now when I want to test Service_A and Service_B, do I again need to create a spy for my Service_MAIN and pass httpClientspy, routerSpy, etc.?

Also, if I once create a spy for Service_MAIN in order to test Service_A, do I need to create the same spy for Service_B as well?

It would create a lot of repetition in my test files.

NOTE: Service_A does not directly use HTTPCLIENT, it uses the Service_MAIN to make HTTP calls indirectly.

Body:
When testing Service_A or Service_B, you can create a spyObj for Service_MAIN and mock the public methods of it that Service_A or Service_B depends on.

An example for testing Service_A.

let service: Service_A;
let mockServiceMain: any

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('serviceMain', [/* Put the public methods of serviceMain here as comma separated strings*/]);

    TestBed.configureTestingModule({
      imports: [],
      providers: [
        // Inject the actual service because it is to be tested
        Service_A,
        // when the service requests for Service_MAIN, use the mock value
        { provide: Service_MAIN, useValue: mockServiceMain },
        // your other providers or mock providers can go here
      ]
    });
    service = TestBed.inject(Service_A);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

Also for the router, you should import RouterTestingModule and not stub it (https://angular.io/api/router/testing/RouterTestingModule). Same thing goes for HTTP, you should use HttpTestingController (https://angular.io/api/common/http/testing/HttpTestingController).


问:
Javascript form validation
How do I let users know that "there are changes left to be saved on the form if they try to close the browser window?"

I have a form with couple of fields, Now if the user changes some of the fields and clicks on Close button on the browser window, my script should alert him of unsaved changes. How do I implement this? I have put in basic form validation but can't seem to think of a solution for window.close() event. Any sample links would be helpful.

答:
Well you could use the body onbeforeunload or onunload.

```<code><body onBeforeUnload="return(confirm('unsaved stuff'))">
</code>```

Never used a return to stop a page unload before but it should work.

Update:

In the header of the web page to make it a global var:

```<code><script type="text/javascript">
var formData = [];
function saveForm(){
    var data = [];
    for(var index = 1; index <= 3; index++){
        data [index - 1] = document.getElementById("textfield_" + index).value;
    }
    return(data);
}

function unsavedData(){
    var newFormData = saveForm();
    for(var index = 0; index < 2; index++){
        if(formData[index] != newFormData[index]){
            return(confirm("Unsaved data, do you really want to exit?"));
        }
    }
    return(true);
}
</script>
</code>```

In the body(of course):

```<code><body onBeforeUnload="return(unsavedData())">
...
<form ... onSubmit="formData = saveForm()">
<input type="text" id="textfield_1">
<input type="text" id="textfield_2">
<input type="text" id="textfield_3">
/*form submit button*/
</form>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript form validation

Body:
Well you could use the body onbeforeunload or onunload.

<body onBeforeUnload="return(confirm('unsaved stuff'))">

Never used a return to stop a page unload before but it should work.

Update:

In the header of the web page to make it a global var:

<script type="text/javascript">
var formData = [];
function saveForm(){
    var data = [];
    for(var index = 1; index <= 3; index++){
        data [index - 1] = document.getElementById("textfield_" + index).value;
    }
    return(data);
}

function unsavedData(){
    var newFormData = saveForm();
    for(var index = 0; index < 2; index++){
        if(formData[index] != newFormData[index]){
            return(confirm("Unsaved data, do you really want to exit?"));
        }
    }
    return(true);
}
</script>

In the body(of course):

<body onBeforeUnload="return(unsavedData())">
...
<form ... onSubmit="formData = saveForm()">
<input type="text" id="textfield_1">
<input type="text" id="textfield_2">
<input type="text" id="textfield_3">
/*form submit button*/
</form>


问:
How to implement decorator Pattern with Autofac for the below scenario
I need to implement decorator pattern using Autofac.

I have two classes/services with their own implementation. Now based on a condition I need to be able to call either of the service class dynamically to get the data.

```<code>ServiceClassA : InterfaceA
{
   // Method A
}

ServiceClassB : InterfaceB
{
  //Method B
}
</code>```

Currently I have the Registered the ServiceClassA and ServiceClassB like below

```<code>builder.RegisterType<ServiceClassA>()
       .WithParameter( new resolvedParameter())
       .As<InterfaceA>()
       .InstancePerLifeTimeScope();

builder
       .RegisterType<ServiceClassB>()
       .As<InterfaceB>()
       .InstancePerLifetimeScope();
</code>```

The ServiceClassA is called from within the controller (ControllerClass) like below

```<code>ControllerClass : Controller
{
  private readonly InterfaceA _serviceClassA;
  public Controller(Interface serviceClassA)
  {
    _serviceClassA = serviceClassA;
  }

  public ActionResult Get()
  {
   var obj = _serviceClassA.MethodA();
  }
}
</code>```

When the above call is made, based on a condition (date > 31st March 2020 ) the method B in ServiceClassB should be called. To achieve this our technical architect thinks decorator pattern with Autofac is the solution with little impact for the existing flow of the code.

So I made the below changes for the ServiceClassA registration

```<code>builder.RegisterType<ServiceClassA>()
           .WithParameter( new resolvedParameter())
           .Named<InterfaceA>("serviceClassA")
           .InstancePerLifeTimeScope();
 builder.RegisterDecorator<InterfaceA>(
            (c,serviceClassA) => ServiceDecorator(),
            "serviceClassA");
</code>```

after the above steps I am stuck, dont know where how to apply the condition. Checked a lot of answers on stackoverflow to find the solution not able to.

答:
The decorator pattern relies on both classes implementing the same Interface. Not as you described above. E. G.

public interface IProductRepository
{
  Product Get(int id);
}

public class ProductRepository : IProductRepository
{
  public Product Get(string id)
  {
    // logic to get product
  }
}

public class LoggingProductRepository : IProductRepository
{
  private IProductRepository _productRepository;
  private ILog _logger;

  public LoggingProductRepository(IProductRepository productRepository, ILog logger)
  {
    _productRepository = productRepository;
    _logger = logger;
  }

  public Product Get(string id)
  {
     _logger.Log("something");
     return _productRepository.Get(id);
  }
}
```

Body:
I need to implement decorator pattern using Autofac.

I have two classes/services with their own implementation. Now based on a condition I need to be able to call either of the service class dynamically to get the data.

ServiceClassA : InterfaceA
{
   // Method A
}

ServiceClassB : InterfaceB
{
  //Method B
}

Currently I have the Registered the ServiceClassA and ServiceClassB like below

builder.RegisterType<ServiceClassA>()
       .WithParameter( new resolvedParameter())
       .As<InterfaceA>()
       .InstancePerLifeTimeScope();

builder
       .RegisterType<ServiceClassB>()
       .As<InterfaceB>()
       .InstancePerLifetimeScope();

The ServiceClassA is called from within the controller (ControllerClass) like below

ControllerClass : Controller
{
  private readonly InterfaceA _serviceClassA;
  public Controller(Interface serviceClassA)
  {
    _serviceClassA = serviceClassA;
  }

  public ActionResult Get()
  {
   var obj = _serviceClassA.MethodA();
  }
}

When the above call is made, based on a condition (date > 31st March 2020 ) the method B in ServiceClassB should be called. To achieve this our technical architect thinks decorator pattern with Autofac is the solution with little impact for the existing flow of the code.

So I made the below changes for the ServiceClassA registration

builder.RegisterType<ServiceClassA>()
           .WithParameter( new resolvedParameter())
           .Named<InterfaceA>("serviceClassA")
           .InstancePerLifeTimeScope();
 builder.RegisterDecorator<InterfaceA>(
            (c,serviceClassA) => ServiceDecorator(),
            "serviceClassA");

after the above steps I am stuck, dont know where how to apply the condition. Checked a lot of answers on stackoverflow to find the solution not able to.


问:
Add image before bookdown title
I'm trying to add an image before the title in gitbook style bookdown project. This is similar to this question from the RStudio Community page, but I would like the image to appear only before the title, not every top-level heading.

I've created a reprex here: https://bd-reprex.netlify.app/

I've edited the _output.yml to include:

```<code>bookdown::gitbook:
  ...
  includes:
    before_body: assets/logo.html
</code>```

However, as can be seen in the example above, the image now appears before every chapter, not just before the title.

Any help would be greatly appreciated!

答:
This question was answered here.

The solution is to add a JS codeblock to the end of the index.Rmd file, such as

```<code>```{js, echo = FALSE}
title=document.getElementById('header');
title.innerHTML = '' + title.innerHTML
```
</code>```

Title: Add image before bookdown title

Body:
I'm trying to add an image before the title in gitbook style bookdown project. This is similar to this question from the RStudio Community page, but I would like the image to appear only before the title, not every top-level heading.

I've created a reprex here: https://bd-reprex.netlify.app/

I've edited the _output.yml to include:

bookdown::gitbook:
  ...
  includes:
    before_body: assets/logo.html

However, as can be seen in the example above, the image now appears before every chapter, not just before the title.

Any help would be greatly appreciated!

Body:
This question was answered here.

The solution is to add a JS codeblock to the end of the index.Rmd file, such as

```{js, echo = FALSE}
title=document.getElementById('header');
title.innerHTML = '<img src="/path/to/img.png" alt="Test Image">' + title.innerHTML
```


问:
How to return a file to download in Java using Undertow?
I am trying to allow my game client to download the cache needed for the client to run. Inside of my game web server I am doing this:

```<code>@RouteManifest(template="/cache", method="GET")
public class APICacheRoute extends RouteHttpHandler<JadePreprocessor> {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        Path path = Paths.get("./cache/Alterscape.zip");
        File file = path.toFile();
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
        exchange.getResponseSender().send(file);
    }
}
</code>```

However, I am receiving the error that the file must be a ByteBuffer. How can I return a file to download?

My web server looks like this:

```<code>public static void initialize() {
    ServerController server = new ServerController("localhost", 8080, 8443);
    server.register(new APIVirtualHost());
    server.inititialize();
}
</code>```

My APIVirtualHost looks like this:

```<code>public APIVirtualHost() {
    super(127.0.0.1);
    setDirectoryListingEnabled(false);
}
</code>```

答:
Try to wrap your own handler with this io.undertow.server.handlers.BlockingHandler. It already contains the necessary checks before performing a blocking operation.

```<code>public final class BlockingHandler implements HttpHandler {
    ...
    @Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {

        exchange.startBlocking();
        if (exchange.isInIoThread()) {
            exchange.dispatch(handler);
        } else {
            handler.handleRequest(exchange);
        }
    }
    ...
}
</code>```

Body:
I am trying to allow my game client to download the cache needed for the client to run. Inside of my game web server I am doing this:

@RouteManifest(template="/cache", method="GET")
public class APICacheRoute extends RouteHttpHandler<JadePreprocessor> {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        Path path = Paths.get("./cache/Alterscape.zip");
        File file = path.toFile();
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
        exchange.getResponseSender().send(file);
    }
}

However, I am receiving the error that the file must be a ByteBuffer. How can I return a file to download?

My web server looks like this:

public static void initialize() {
    ServerController server = new ServerController("localhost", 8080, 8443);
    server.register(new APIVirtualHost());
    server.inititialize();
}

My APIVirtualHost looks like this:

public APIVirtualHost() {
    super(127.0.0.1);
    setDirectoryListingEnabled(false);
}

Body:
Try to wrap your own handler with this io.undertow.server.handlers.BlockingHandler. It already contains the necessary checks before performing a blocking operation.

public final class BlockingHandler implements HttpHandler {
    ...
    @Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {

        exchange.startBlocking();
        if (exchange.isInIoThread()) {
            exchange.dispatch(handler);
        } else {
            handler.handleRequest(exchange);
        }
    }
    ...
}


问:
Is possible drag drop files into standard html textarea?
I would like to know if it possible add drag and drop files to a standard HTML tag <textarea> and the same time it have the write too? Similiar stackoverflow textarea

答:
If you're using HTML5, you can drag and drop text content as follows:

CSS:

```<code>#tadrop{
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
</code>```

Javascript:

```<code>function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.value = document.getElementById(data).innerHTML;
  //jQuery: ev.target.value = $('#'+data).text();
}
</code>```

HTML:

```<code><p>Drag SOME TEXT into the rectangle:</p>

<textarea id="tadrop" ondrop="drop(event)" ondragover="allowDrop(event)"></textarea>

<p id="drag1" draggable="true" ondragstart="drag(event)">SOME TEXT</p>
</code>```

Here's fiddle: text drag and drop to textarea.

Body:
If you're using HTML5, you can drag and drop text content as follows:

CSS:

#tadrop{
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}

Javascript:

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.value = document.getElementById(data).innerHTML;
  //jQuery: ev.target.value = $('#'+data).text();
}

HTML:

<p>Drag SOME TEXT into the rectangle:</p>

<textarea id="tadrop" ondrop="drop(event)" ondragover="allowDrop(event)"></textarea>

<p id="drag1" draggable="true" ondragstart="drag(event)">SOME TEXT</p>

Here's fiddle: text drag and drop to textarea.


问:
dash ( - ) in where clause with sleep function
In MySQL you can pause a result for x seconds with the SLEEP function.

I understand when you use it like this:

```<code>SELECT SLEEP(1000);
</code>```

But I recently saw that you can enhance a query in this form:

```<code>mysql> select * from docs where rev = 1-sleep(4);
</code>```

and it will wait 4 seconds before it returns the results in comparison to

```<code>mysql> select * from docs where rev = 1;
</code>```

Why is this so? Is the dash a form of concatenating functions or something like this? I couldn't find any explanation for this syntax.

I reproduced this query using docker

```<code>docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest
docker exec -ti some-mysql mysql -uroot -pmy-secret-pw
</code>```

and the following code to create the table (using code from sql fiddle) and verify the behavior.

```<code>CREATE test;
USE test;
CREATE TABLE IF NOT EXISTS `docs` (
  `id` int(6) unsigned NOT NULL,
  `rev` int(3) unsigned NOT NULL,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`rev`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`id`, `rev`, `content`) VALUES
  ('1', '1', 'The earth is flat'),
  ('2', '1', 'One hundred angels can dance on the head of a pin'),
  ('1', '2', 'The earth is flat and rests on a bull\'s horn'),
  ('1', '3', 'The earth is like a ball.');
select * from docs where rev = 1;
select * from docs where rev = 1-sleep(4);
</code>```

答: As you can read in the manual you've linked, SLEEP returns 0. So using it in some kind of calculation like where rev = 1-sleep(4); triggers the execution of SLEEP (as in: waits four seconds). Afterwards, the query is resumed with where rev = 1-0, making it equal to where rev = 1

Body:
In MySQL you can pause a result for x seconds with the SLEEP function.

I understand when you use it like this:

SELECT SLEEP(1000);

But I recently saw that you can enhance a query in this form:

mysql> select * from docs where rev = 1-sleep(4);

and it will wait 4 seconds before it returns the results in comparison to

mysql> select * from docs where rev = 1;

Why is this so? Is the dash a form of concatenating functions or something like this? I couldn't find any explanation for this syntax.

I reproduced this query using docker

docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest
docker exec -ti some-mysql mysql -uroot -pmy-secret-pw

and the following code to create the table (using code from sql fiddle) and verify the behavior.

CREATE test;
USE test;
CREATE TABLE IF NOT EXISTS `docs` (
  `id` int(6) unsigned NOT NULL,
  `rev` int(3) unsigned NOT NULL,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`rev`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`id`, `rev`, `content`) VALUES
  ('1', '1', 'The earth is flat'),
  ('2', '1', 'One hundred angels can dance on the head of a pin'),
  ('1', '2', 'The earth is flat and rests on a bull\'s horn'),
  ('1', '3', 'The earth is like a ball.');
select * from docs where rev = 1;
select * from docs where rev = 1-sleep(4);