简体   繁体   中英

How to use Database.Migration() after Database.EnsureCreated() EF Xamarin.Forms

I was working on a Xamarin.Forms application and using EF 6 targeting .net standard 2.0 . The application is live on app store with my DBContext class as follows.

public class DatabaseContext : DbContext
{
    private readonly string _databasePath;

    // Hotworks related tables
    public DbSet<User> User { get; set; }
    public DbSet<UserProfile> UserProfile { get; set; }

    public DatabaseContext(string databasePath)
    {
        _databasePath = databasePath;
        Database.EnsureCreated();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite($"Filename={_databasePath}");    
    }
}

Now, I have to add a new column to the User Table. For that, I have created a .net core console application and generated the migration folder using below commands.

dotnet ef migrations add Initial
dotnet ef update database

Then, I copied the generated Migration folder to my dbContext project and changed the Database.EnsureCreated() to Database.Migration() But, I'm getting SQLite error 1: Table "User" already exists . Any help? Code already in the production having Database.EnsureCreated() but now I have to migrate and update the database but, it is not working and always I'm getting the table already exist error.

Here's a safer approach compared to my previous comment

  1. add-migration Initial for the models that is equivalent to the production database (ie without the newly added column in User table and other changes that you did after deploying to production).
  2. Manually update the production database __EFMigrationsHistory to include the Initial migration.
  3. add-migration XXX for the updated schema (ie new columns, etc).
  4. XXX should then be applied to your production database by the Database.EnsureMigrate() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM