【问题标题】:How to enable migration in EntityFramework Core Sqlite如何在 EntityFramework Core Sqlite 中启用迁移
【发布时间】:2019-08-15 02:30:14
【问题描述】:

我有 Dbset 并像这样创建数据库。当第一次创建 db 然后在 dbset 中添加列之后,迁移不起作用,找不到表列。请帮助我如何在 Xamarin Forms 中启用 EF Core Sqlite 迁移。

public  BaseSQLRespository(string databasePath)
{
    try
    {
        _databasePath = databasePath;

        Database.EnsureCreated();

        // bool IsDatabaseCreated= ;
        // Settings.IsDatabaseCreatedSettings = IsDatabaseCreated;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    try
    {
        optionsBuilder.UseSqlite(string.Format("Filename={0}", _databasePath));
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

【问题讨论】:

    标签: xamarin.forms entity-framework-core-migrations


    【解决方案1】:

    假设您使用add-migration 命令为新列创建了迁移,您可以通过调用Migrate() 方法而不是EnsureCreated() 在运行时启用迁移的执行。该方法的文档可以在here找到。

    根据 Microsoft 的文档,Migrate 方法与 EnsureCreated 方法不兼容,后者在创建数据库架构时实际上绕过了迁移 - 所以在您的情况下,您将不得不删除旧数据库(卸载应用程序或清除它是数据)在尝试新代码之前。

    不要在Migrate() 之前调用EnsureCreated()EnsureCreated() 绕过迁移来创建架构,这会导致 Migrate() 失败。

    来源:EF Core - Apply migrations at runtime

    【讨论】:

    • 我检查了给定的来源,但没有提到 EnsureCreated(它可能在过去)。尽管如此,你的帖子让我找到了其他来源,也解决了我遇到的一个长期存在的问题,所以我希望我能给出更多的 +1。如果您想将此添加为额外的source,它也可能对其他人有所帮助。
    • 如果我的消息来源消失了,这里是它的简历和GitHub上提出的相关问题的链接
    • EnsureCreated 完全绕过了迁移,只是为你创建了模式,你不能把它和迁移混在一起。 EnsureCreated 专为测试或快速原型设计而设计,您每次都可以删除和重新创建数据库。如果您正在使用迁移并希望在应用启动时自动应用它们,那么您可以改用 context.Database.Migrate()。
    【解决方案2】:

    要添加初始迁移,请运行以下命令:

    dotnet ef migrations add YourNameOfMigration
    

    接下来,将迁移应用到数据库以创建架构:

    dotnet ef database update
    

    Migrations

    每次向模型添加新字段时,都应添加迁移并将其应用到 DB。

    【讨论】:

      【解决方案3】:

      我猜你的配置是错误的,你不应该在ctor中调用Database.EnsureCreated();,因为OnConfiguring()还没有被调用并且你的数据库没有被初始化。

      您可以创建一个在您的 serviceProvider 启动后调用的方法。

      
         public static void Initialize(IServiceProvider serviceProvider)
         {
                  var context = serviceProvider.GetRequiredService<BaseSQLRespository>();//use your service provider any thing which you can get your current created `BaseSQLRespository`
                  context.Database.EnsureCreated();//once call when your app is started. (it is up to you which method you used to call)
         ...
         ...
         }
      
      

      此外,这里有类似的主题和不同的解决方案, 你可以查看:Error in Database.EnsureCreated() while using Entity Framework with Sqlite in Xamarin

      【讨论】:

        猜你喜欢
        • 2019-11-21
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 2017-01-07
        • 2020-09-29
        • 2018-03-01
        • 2016-09-06
        • 1970-01-01
        相关资源
        最近更新 更多