EF6 与 MySQL.字典中不存在给定的键

EF6 with MySQL. The given key was not present in the dictionary(EF6 与 MySQL.字典中不存在给定的键)
本文介绍了EF6 与 MySQL.字典中不存在给定的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用 Code First Entity Framework 6 的 Asp.Net MVC 5 应用程序链接到 MySQL 数据库.

I have Asp.Net MVC 5 application using Code First Entity Framework 6 linked to MySQL database.

当我第一次创建数据库时,它工作正常.但是当我对模型进行更改时,然后添加迁移.(Update-Database) 之后显示错误.

When I created the database first time, it works fine. But when I make a change to the model then add migration. An error shows after (Update-Database).

这是错误:

        PM> Update-Database 
        System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
           at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
           at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.<>c.<.cctor>b__2_7(MySqlConnectionStringBuilder msb, MySqlConnectionStringOption sender)
           at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.get_Item(String keyword)
           at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.GetConnectionString(Boolean includePass)
           at MySql.Data.MySqlClient.MySqlConnection.get_ConnectionString()
           at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<GetConnectionString>b__12(DbConnection t, DbConnectionInterceptionContext`1 c)
           at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget, TInterceptionContext, TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
           at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.GetConnectionString(DbConnection connection, DbInterceptionContext interceptionContext)
           at System.Data.Entity.Internal.InternalConnection.GetStoreConnectionString(DbConnection connection)
           at System.Data.Entity.Internal.InternalConnection.OnConnectionInitialized()
           at System.Data.Entity.Internal.EagerInternalConnection..ctor(DbContext context, DbConnection existingConnection, Boolean connectionOwned)
           at System.Data.Entity.DbContext..ctor(DbConnection existingConnection, Boolean contextOwnsConnection)
           at System.Data.Entity.Migrations.History.HistoryContext..ctor(DbConnection existingConnection, String defaultSchema)
           at MySql.Data.Entity.MySqlHistoryContext..ctor(DbConnection existingConnection, String defaultSchema)
           at code_first_mysql.Migrations.Configuration.<>c.<.ctor>b__0_0(DbConnection conn, String schema) in C:UsersUserDocumentsTreeNew Backendcode first mysqlMigrationsConfiguration.cs:line 16
           at System.Data.Entity.Migrations.History.HistoryRepository.CreateContext(DbConnection connection, String schema)
           at System.Data.Entity.Migrations.History.HistoryRepository.<GetUpgradeOperations>d__16.MoveNext()
           at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
           at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
           at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
           at System.Data.Entity.Migrations.Infrastructure.MigratorScriptingDecorator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
           at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
           at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
           at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
           at System.Data.Entity.Migrations.Infrastructure.MigratorScriptingDecorator.ScriptUpdate(String sourceMigration, String targetMigration)
           at System.Data.Entity.Migrations.Design.ToolingFacade.ScriptUpdateRunner.Run()
           at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
           at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
           at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
           at System.Data.Entity.Migrations.Design.ToolingFacade.ScriptUpdate(String sourceMigration, String targetMigration, Boolean force)
           at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
           at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
        The given key was not present in the dictionary.

这些是我的 MySQL 配置类:

These are my MySQL Configuration Classes:

internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
        SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
        CodeGenerator = new MySqlMigrationCodeGenerator();
    }

    protected override void Seed(ApplicationDbContext context)
    {}
}


public class MySqlConfiguration: DbConfiguration
{

    public MySqlConfiguration()
    {
        SetHistoryContext("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
    }

}



public class MySqlHistoryContext : HistoryContext 
{
    public MySqlHistoryContext(DbConnection existingConnection, string defaultSchema) : base(existingConnection, defaultSchema)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
        modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
    }
}

 public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{

    public void InitializeDatabase(ApplicationDbContext context)
    {
        if (!context.Database.Exists())
        {
            // if database did not exist before - create it
            context.Database.Create();
        }
        else
        {
            // query to check if MigrationHistory table is present in the database 
            var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
            string.Format(
              "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'", "mydb"));

            // if MigrationHistory table is not there (which is the case first time we run) - create it
            if (migrationHistoryTableExists.FirstOrDefault() == 0)
            {
                context.Database.Delete();
                context.Database.Create();
            }
        }
    }
}

推荐答案

从错误的第一行可以看出,

As you see from the first lines of the error,

MySql.Data.MySqlClient.MySqlConnectionStringBuilder.<>c.<.cctor>b__2_7(MySqlConnectionStringBuildermsb,MySqlConnectionStringOption 发件人)在 MySql.Data.MySqlClient.MySqlConnectionStringBuilder.get_Item(字符串关键字)

MySql.Data.MySqlClient.MySqlConnectionStringBuilder.<>c.<.cctor>b__2_7(MySqlConnectionStringBuilder msb, MySqlConnectionStringOption sender) at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.get_Item(String keyword)

错误与 ConnectionString 有关.问题是 ConnectionString 包含无法读取的键.

the error has to do with the ConnectionString. The problem is the ConnectionString contains keys that can't be read.

尝试清理 ConnectionString 使其只有

  1. 服务器
  2. 用户 ID
  3. 密码
  4. 数据库

在我的例子中,ConnectionString 有一个额外的密钥integrated security.当这被删除 Update-Database 开始工作正常.但是,根据您的情况,这可能是也可能不是导致错误的关键.

In my case, the ConnectionString had an extra key integrated security. When this was removed Update-Database started working fine. Depending on your case however, this might and might not be the key that caused the error.

所以我再次提出并保证解决方案,检查 ConnectionString 并简化它,使其仅包含上面提到的 4 个键.

So again my proposed and guaranteed solution, go through ConnectionString and simplify it so that it contains only the 4 keys mentioned above.

这篇关于EF6 与 MySQL.字典中不存在给定的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)