【问题标题】:MySQL, EF6 and Database.CreateIfNotExistsMySQL、EF6 和 Database.CreateIfNotExists
【发布时间】:2019-07-24 18:13:22
【问题描述】:

我遇到了 MySQL 不使用 EF6 创建数据库的问题。此代码在 MSSQL Server 中运行良好(只需将提供程序更改为“System.Data.SqlClient”):

public class MyDbContext : DbContext
{
    public MyDbContext(string connectionString)
        : base(GetConnection(connectionString),true)
    {
        Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());

        //Database.Initialize(true);
        Database.CreateIfNotExists();
    }

    public DbSet<MyData> MyData { get; set; }

    public static DbConnection GetConnection(string connectionString)
    {
        var factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");

        var connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;
        return connection;
    }

}

问题出在“Database.CreateIfNotExists();”行中。它抛出一个 NullReferenceException ......“Database.Initialize(true);”并且“Database.CreateIfNotExists()”会抛出同样的错误。

我的连接字符串是:

Server=localhost;Database=MyDatabase;Uid=myUser;Pwd=myPassword;

完全相同的代码在 SQL Server 上运行良好。我什至删除了数据库,然后 SQL Server 重新创建了它。

做一些测试,使用 MySQL Shell,我手动创建了“MyDatabase”,没有发生错误,但是没有创建表。

我需要一些额外的代码来让 MySQL 自动创建数据库和表吗?

其他测试:我已添加此代码:

if (!Database.Exists())
{
   Database.Create();
}

“Database.Exists()”工作正常,问题出在“.Database.Create()”。真的,我觉得我在这里遗漏了一些东西。

* 编辑 * 我的应用程序配置。 (我没有使用 app.config 中的连接字符串)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.10.8.0" newVersion="6.10.8.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

【问题讨论】:

  • 能否请您出示您的 web.config 或 app.config?
  • @er-sho 完成。但我没有从那里得到连接字符串
  • 只需在您的 DbContext 类上方添加此属性并尝试再次启用迁移 => [DbConfigurationType(typeof(MySqlEFConfiguration))]
  • @er-sho “再次启用迁移”是什么意思?在 MySql 中是必需的吗?在 Sql Server 中,它按原样工作......
  • 你先编码对吗?因为你添加了标签ef-code-first所以代码首先需要迁移。

标签: c# mysql entity-framework-6 ef-code-first mysql-connector


【解决方案1】:

找到了!阅读 MySql 文档 here,我做了 2 处更改:

(1) 将第二个构造函数添加到我的 DbContext:

// Constructor to use on a DbConnection that is already opened
public MyDbContext(DbConnection existingConnection, bool contextOwnsConnection)
   : base(existingConnection, contextOwnsConnection)
{
}

(2) 使用这个新的构造函数,生成数据库的代码是:

using (MySqlConnection connection = new MySqlConnection(myConnectionString))
{
   using (MyDbContext contextDB = new MyDbContext(connection, false))
   {
      contextDB.Database.CreateIfNotExists();
   }
}

希望对大家有所帮助!

【讨论】:

    【解决方案2】:

    创建数据库之前是否打开连接?

    SqlConnection connection = new SqlConnection(connectionString);
    
    connection.Open();
    
    //Do stuf with database...
    

    【讨论】:

    • 我现在测试了。尝试打开连接时收到此异常:“使用方法 'caching_sha2_password' 对用户 'myUser' 的主机 'localhost' 进行身份验证失败,并显示消息:未知数据库 'MyDatabase'”
    • 好像无法连接数据库,检查连接字符串是否有错误,确保格式正确。
    猜你喜欢
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    相关资源
    最近更新 更多