Home > Back-end >  Updating a SQLite Database to reflect a change to the model with Entity Framework Core and .NET 6
Updating a SQLite Database to reflect a change to the model with Entity Framework Core and .NET 6

Time:06-24

I've created a dbcontext that looks like this:

public class DatabaseContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    public DbSet<Book> Books { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(@"Data Source=E:\Portfolio\FullStack\HomeLibraryManager\Database\Library.db;");
    }
}

And I Initialize it like this:

using (var context = new DatabaseContext())
{
    context.Database.EnsureCreated();
    var books = context.Books.ToList();
}

I would like to add a variable to my Book class but how do I get the database table to have that new variable added as a column.

I had hoped that EnsureCreated() would make sure the table columns were updated if needed but it seems not.

Any help would be great,

thanks

Edit Solution: I used context.Database.Migrate(); instead of EnsureCreated and ran dotnet-ef migrations add [MigrationNameHere] first

CodePudding user response:

Run the Add-Migration AddUrl command in Package Manager Console. The Add-Migration command checks for changes since your last migration and scaffolds a new migration with any changes that are found. We can give migrations a name; in this case we are calling the migration ‘AddUrl’. The scaffolded code is saying that we need to add a Url column, that can hold string data, to the dbo.Blogs table. If needed, we could edit the scaffolded code but that’s not required in this case.

Run the Update-Database command in Package Manager Console. This command will apply any pending migrations to the database. Our InitialCreate migration has already been applied so migrations will just apply our new AddUrl migration. Tip: You can use the –Verbose switch when calling Update-Database to see the SQL that is being executed against the database.

Dealing with Model Changes

  • Related