Entity Framework Core database migration in C# - c#

I'm trying to migrate a database (the database was already created beforehand) through the startup of an ASP.NET Core 3.1 web app. I created the migration by enabling migrations in the Visual Studio Package Manager Console:
enable-migrations
And then created a migration:
Add-Migration TestTable –Context MyDbContext
TestTable creates a simple table that I use to test the migration.
I want to be able to migrate the database on startup, without the need to use the Visual Studio Package Manager Console, without the need to use the update-database command.
I have tried this:
var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("MyConnectionString"),
sql => sql.MigrationAssembly(migrationAssembly))));
I get no errors, but the table never gets created. I tried simple crud operations on the table but they throw error because the table doesn't exist, also I checked in the SQL Server Object Explorer and the table isn't there.
Any thoughts will be greatly appreciated.
Best

Take a look at this code
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
{
// migrate any database changes on startup (includes initial db creation)
dataContext.Database.Migrate();
...
}
here's the reference link:
https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup

Related

How to generate empty migration in Entity Framework Core?

I am using EF Core migrations to upgrade my database schema and my data.
As I write new C# code, I need to change the data in my different database environments: development, test, industrialisation, staging and production.
Because I don't want to execute a SQL script in as many environments I have, my goal is to put some data migration in a C# migration. Then the data migration will be executed with the other schemas migrations. Preventing me from forgetting.
How can I create an empty C# migration script to change my data with calling SQL, even if I have no database change?
Without any changes in data models, when you run the below command, there will be an empty migration file. Then you can put the data manipulation sql code in Up method and revert sql code in Down method :
cli :
dotnet ef migrations add [migrationName]
package manager console :
Add-Migration [migrationName]
You can create an empty migration with the following command in the Package Manager Console:
Add-Migration '[Insert name]'
Your new migration file will look like this:
public partial class [Insert name]: Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}

EF core - Creating a migration for a database without a connection string and in another class library

I want to create a migration for a second and subsequent databases that's in a class library different from the project that uses it. There is a wrinkle. I will never know the connection string until a user logs in and I can get it from a catalog database (saas).
For the catalog database I used the solution from this site. That was fine - This database has its connection string in appsettings.json and can uses dependency injection.
The client databases are all going to be identical using the same migration. My problem is, I dont know how to create this initial migration from the Package Manager Console..
I did try to run this:
dotnet ef migrations add INITIAL --context APIcontext -s ../Jobsledger.API
and its given me the following error:
No database provider has been configured for this DbContext.
Which I expected.
Given that CodingBlast solution (above) to running migrations in a different class library requires a connection which I don't have and requires the database connection to be registered at startup...
..and given that this migration is to be used by every user database to be created how do I create it and of course use it?
I did answer similar question here.
You can implement IDesignTimeDbContextFactory where you instantiate DbContext with no connection string.
For the different library, you can use --project and --startup-project parameters.
Here is an example what I'm using to generate migrations script:
dotnet ef migrations script --context MyDbContext --output migrations.sql --project "./MyApp.Data" --startup-project "./MyApp.Data"

run by default on startup

I'm working with a test project and I'm trying to wrap my head around migrations.
I've created a database with the name: AngularASPNETCore2WebApiAuth
Then in my startup I add a configuration to the Db and point to the Migrations Assembly:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("AngularASPNETCore2WebApiAuth")));
When I start my test project and I Get an error:
System.Data.SqlClient.SqlException: 'Invalid object name 'AspNetUsers'.'
I'm under then Impression that I've provided the MigrationsAssembly so migrations can be run when the project starts.
I'm aware I can update my database through the command line using the Update-Database command.
But why do I have to provide an assembly for migrations in the start up if they're not run by the application by default. How can I run migrations by default on startup?
Setting MigrationsAssembly just tells the context where to find the migrations assembly, you still need to explicity run it (many times you don't want to run migrations every time you start the application). You need to call
myDbContext.Database.Migrate();
To execute the migrations.
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/#apply-migrations-at-runtime

how to properly promote Entity Framework code-first migrations into production?

In my ASP.NET EF 6 app, I have the following Configuration:
internal sealed class Configuration : DbMigrationsConfiguration<Gcim.Management.Module.BusinessObjects.ManagementDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(Gcim.Management.Module.BusinessObjects.ManagementDbContext context)
{
}
}
In my project, I have EF code-first migrations enabled.
I'm able to run add-migration, as well as update-database from the VS Package Manager prompt.
However, when my entities change, adding a migration, and updating database only works in dev environment.
When I publish my ASP.NET project, install it on production IIS, and run, I still get this error:
The model backing the 'ManagementDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
What else do I need to do in order to force the incremental DB changes in production, without data loss?
You can execute a given migration file against a given environment (in this case, your production environment) by using the migrate.exe application included as part of the Entity Framework nuget package. You'll need to execute your latest migration against your production environment before publishing your web application - once this has been done, the newly deployed application will work correctly.
You do this by specifying the connection string and .dll containing the migration class(es), as well as possibly a specific migration. For example:
Migrate.exe Gcim.Management.Module.BusinessObjects.dll /connectionString="Data Source=[YourProductionDatabase];Initial Catalog=[YourTable];Integrated Security=SSPI" /connectionProviderName="System.Data.SqlClient" /targetMigration="[NameofYourMigration]"
Documentation on migrate.exe can be found here: https://msdn.microsoft.com/en-us/data/jj618307.aspx

Code based DB migration in Entity Framework 6.1.2: How to avoid using powershell commands?

I am using EF 6.1.2, to do Code based DB migration there are some commands we need to excecute. Which are: Add-Migration and Update-Database. I want this migration to happen in production environment. So is there any way to avoid Update-Database command in Package Manager Console and use C# APIs to do the same?
I can not use Update-Database command in production environment. And I want an aleternate to it in c#.
There is an obvious alternative, you can have the MigrateDatabaseToLatestVersion for this particular db context.
This way the migration happens automatically when a very first query is executed against the database. You could even have a separate commandline tool that does the same but is executed at the production environment on demand (rather than when the app executes the very first query), prior to application.
The initializer is straightforward to use, just call:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<YourContext, Configuration>());
where Configuration is the class that keeps the configuration of your migrations.

Categories