run by default on startup - c#

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

Related

"Update-Database" command does not update to the latest version of Migration

I am trying to use Migrations in my project but when trying to update the database, only the base migration is applied.
I have a total of two migrations.
The Base migration(initialy created)
CreateNewProperty(Change includes adding a new property to one of the tables)
I see Enable-Migration mentioned in the Microsoft Documentation but it seems to have gone obsolete.
In addition to this, I also a mention of using the following in the Context class to enable latest migrations, but SetInitialier() method is no longer available:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, EF6Console.Migrations.Configuration>());
When I try to remove all migrations and bring it to the initial state by executing:
update-databse 0
it fails with the following error:
ALTER TABLE DROP COLUMN failed because column 'test' does not exist in
table 'Item'.
which is basically the update done in the CreateNewproperty migration and this error is expected as this migration was never applied. Why is EF trying to downgrade a migration, when it did not apply it in the first place.
Use below command to Migrate to a Specific Version (Including Downgrade)
update-database -targetmigration:MigrationName
More information visit
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/#migrate-to-a-specific-version-including-downgrade
Is it possible that your snapshot has become messed up somehow? You could try deleting that and then create a new migration (one that you could throw away) to rebuild it. Then try running update-database again.
In order to get rid of writing Migration and Update commands each time your data model changes, you can simply write two command line files as EF CLI and just click them to execute Migration and Update commands. These command files create the Migration name using the date and time of your machine.
For the add migration file set a name such as 01-add_migration.cmd (with .cmd extension) with the following content:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c_%%a_%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME: =0%") do (set mytime=%%a%%b)
dotnet ef --startup-project ../Product.Api migrations add V%mydate%_%mytime% -o Persistence/Migrations -c ApplicationDbContext
pause
and for the update database set e file name such as 02-update_db.cmd with the content as bellow:
dotnet ef --startup-project ../Product.Api database update -c ApplicationDbContext
pause
You can add other parameters of Migration and Update commands as well.
So in my opinion, if you have created lots of migrations and started changing up the classes during the creation of your app, you might have missed something, which happens to many developers.
If that is your case, you should try to delete the migrations history in the database and the tables that were created using the migrations.
The migrations history table is located in the tables folder of the database and looks like this:
Then delete the migrations folder that you have in your Project.
Search for it in the solution explorer.
It should look something like this:
Next, do what you would do from the beginning.
Add-Migration [Name]
Update-Database
Okay, so this is what worked:
I deleted the database completely and then ran the update-databse command.
On running this, first the base migration was applied and then the second migration. And now when I create a third migration and apply it is working as expected!

Enabling Database Migrations with 2 Local Dbs

I'm after running into a problem with using Database-Migrations on my asp.net mvc project because I am using 2 local databases. I now have 2 databases; 1 which was created on project startup for identity user management like users, user roles etc. (aspnet-IdentityTest-201~). I Enabled-Migrations on this database in order to Seed() an admin member into it and everything was working fine.
The 2nd database was created after this using the code first database approach to store model data. Now my question, since my project already has migrations enabled (on the 1st Db), how do I enable migrations on my 2nd Db also? Currently when I run Update-Database, it targets 'aspnet-IdentityTest-20190707071058'. I would like to be able to run this command for my 'IdentityTest.Models.TestDb' also (with automatic migration enabled).
I'm afraid to run 'Enable-Migrations -ContextTypeName IdentityTest.Models.TestDb' again as the last time I did this, it deleted my current config.cs file which included my Seed() for admins and I was left with a new config file for just the TestDb context. The project also failed to build after this
Could somebody please advise if there a way for my 2 databases to have migrations enabled? Do they have to share the same migrations/config.cs file? If this is not possible, using the code first approach; how do I make my project use aspnet-IdentityTest-201~ Db for storing model information instead of creating a new Db like it did with IdentityTest.Models.TestDb?
Thanks in advance!
First I took a solution where I successfully code firsted a db. I changed all occurrences of my db name and suffix it with 2db. I create another connection and call it {..}2 with catalog name {..}2dbSecond. I then delete my Migrations folder. I split out my context file into two contexts and have DbSet<> included in each appropriately.
typed:
enable-migrations -projectname contosouniversitydal -contexttypename schoolcontext
in the added migrations folder, in configration.cs, added the a seed method
Add-Migration InitialCreateContext1 -ProjectName contosouniversitydal -configurationtypename configuration -connectionstring schoolcontext
Update-database -projectname contosouniversitydal -configurationtypename configuration -connectionstringname schoolcontext
I then do the similar for the other context.
You can use https://coding.abel.nu/2012/03/ef-migrations-command-reference
Enable-Migrations has a -MigrationsDirectory option, so you can split among two different databases.

ASP.NET Core 2 Migrations don't work on new machine with empty database

I created a ASP.NET Core 2 project, created some migrations along the way, and pushed the code up to a repository.
Today, I pulled the code to another computer I have for development, the database was obviously not created on the new machine so I created a empty database locally to match the connection string.
Now, when trying to run the code "dotnet ef database update" I get this error:
An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Invalid object name 'AspNetUsers'.)
Unable to create an object of type 'AppDbContext'. Add an
implementation of 'IDesignTimeDbContextFactory' to the
project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time.
Please keep in mind that any "dotnet ef" command I run I have the same error, I tried deleting all the migrations and creating a new one using the "dotnet ef migrations add InitialDb" command, but I still get this error.
I am using Identity in my project and I believe it has to do with this error: (Invalid object name 'AspNetUsers'.)
The commands run without any problem on the machine I initially started to develop the application.
I tried Update-Database from PM with the same result.
Here is an image illustrating the problem:
Thanks in advance.
I found the problem, I had a seeder in the Startup class that was seeding an admin user in case it did not exist.
Because the table did not exist the seeder was failing on each command because it was in the Startup class and was executing all the time.
This issue can be closed.

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.

EF 6 CodeFirst Migrations Not Working

Ok, so I've read the other threads and I'm still not getting anywhere. I have my project set as Startup, I have a connection string in the App.config. I'm using LocalDb in VS2013.
If I delete my database, it creates it ok, BUT, if I try
PM> Enable-Migrations
it tells me that Migrations have already been enabled in project TestCodeFirst. If I then try
PM> Update-Database
it tells me No migrations configuration type was found in the assembly 'TestCodeFirst', and suggests that I try to Enable-Migrations. I have tried adding the -Force parameter. The Migrations folder has only Configuration.cs, and in that file, I've tried setting AutomaticMigrationsEnabled both true and false, with no difference. I'm not lost, cause I can always delete my DB and rerun, but I don't see any way to make the migrations feature work as advertised. Confession: At one point, I took PM's suggestion and tried deleting the Migrations folder. That may have been a mistake.
I have this code snippet in my Program.cs file (I'm just testing this in a console app):
class Program
{
static void Main(string[] args)
{
using (TestContext db = new TestContext())
{
...
Db.ThisOrThat.Add(stuff);
Db.SaveChanges();
...
}
}
}
The Entity Framework Code First approach creates your database automatically, a table will be automatically added to the database by the Code First that is helpful to record the schema of database synchronization with the related model class. Entity Framework throws an error, the database is not synchronized with the class.
To perform the Code First Migration in the database:
Delete the MDF file of the database
Open Package Manager Console and write the following command
Enable-Migrations -ContextTypeName ConsoleApp.Models.TestContext
It creates the Configurations.csclass, then you can edit your code
After Building the application enter the following command in the Package Manager Console:
add-migration Initial
update-database
Note: If you receive an error then you need to ensure that the mdf file is deleted permanently from the App_Data folder. Otherwise you can go to the SQL Server Object Explorer, expand the localDb server and in the Database option ensure that the mdf file is deleted.
Debug the appliction
You'll need to run the "Add-Migration" command that will actually add the migration that the 'Update-Database' command will run:
Code First Migrations
"Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created"

Categories