【问题标题】:Code First with MySQL does not create tables使用 MySQL 的 Code First 不会创建表
【发布时间】:2018-07-31 01:25:10
【问题描述】:

尝试使用实体框架和 MySQL 创建代码优先项目。
当我使用context.Database.EnsureCreated(); 时,表已正确创建,但我想使用迁移,因此代码更改为:context.Database.Migrate();,这就是我收到错误的时候:

MySqlException:表 'library.publishers' 不存在

我确实看到数据库已创建并且有一个空表:__efmigrationshistory 但这是唯一的表,没有发布者喜欢它使用 EnsureCreated。

我在这里错过了什么?

这是重现错误的最少代码:

using Microsoft.EntityFrameworkCore;

namespace mySqlEFcore
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new LibraryContext())
            {
                context.Database.Migrate();
                context.Publishers.Add(new Publisher { ID = 1 });
                context.SaveChanges();
            }
        }

        private class Publisher
        {
            public int ID { get; set; }
        }

        private class LibraryContext : DbContext
        {
            public DbSet<Publisher> Publishers { get; set; }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseMySQL("server=localhost;database=library;user=root;password=123456;SslMode=none;");
            }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Publisher>(entity => { entity.HasKey(e => e.ID); });
            }
        }
    }
}

尝试运行Add-Migration InitialCreate,但遇到更多错误...
添加了引用 Microsoft.EntityFrameworkCore.Design,现在 InitialCreate 显示:

System.MissingMethodException:找不到方法:'无效 Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory..ctor(Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger'1,Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'。 在 MySql.Data.EntityFrameworkCore.Storage.Internal.MySQLCommandBuilderFactory..ctor(IDiagnosticsLogger'1 记录器,IRelationalTypeMapper typeMapper)

【问题讨论】:

  • 被 EF 团队告知这是 Oracle MySQL 包的问题,​​他们建议改用 Pomelo.EntityFrameworkCore.MySql,效果很好!
  • 只是在解决同样的问题,但使用的是 Pomelo.EntityFrameworkCore.MySql 提供程序。你在这方面有什么进展吗?
  • @MichaelKargl Pomelo 包没有问题,这是我的项目:github.com/heldersepu/csharp-proj/tree/PreDocDB/mySqlEFcore
  • 谢谢,不幸的是仍然是相同的“表不存在”。请问你用的是什么版本的mysql和dotnet core?也许我有一个版本不兼容需要解决。
  • @MichaelKargl 是的,第一次获得“表不存在”是可以的,这表明您运行应该创建所有内容的Add-Migration InitialCreate...看看我的项目版本

标签: c# mysql entity-framework .net-core


【解决方案1】:

我有同样的问题。 @Helder Sepulveda 的评论解决了我的问题。 我遵循的步骤:

  1. 打开包管理器控制台
  2. Enable-Migrations
  3. Add-Migration InitialCreate或任何你想要的名字。
  4. Update-Database

然后在我的 MySQL 数据库中创建了这些表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多