首页 > 解决方案 > 如何在 EntityFramework Core Sqlite 中启用迁移

问题描述

我有 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.formsentity-framework-core-migrations

解决方案


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

根据 Microsoft 的文档,该Migrate方法与创建数据库架构时实际绕过迁移的方法不兼容EnsureCreated- 因此在您的情况下,您必须在尝试新代码之前删除旧数据库(卸载应用程序或清除其数据)。

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

来源:EF Core - 在运行时应用迁移


推荐阅读