Entity: automatic migration on Production not working - c#

I have looked at other questions on SO and on blogs and official MS docs but I can't find the proper way.
What I am trying to achieve:
Deploy version 1 of an MVC website with SQL DB (code is based on Entity Code First v. 6.1), without any concept of migration because it's DB SCHEMA v.1
Deploy further versions (2, 3, ..) with automatic migration to SCHEMA v2 (and then v3 etc.) and without running Update-Database in Package Manager console
So, following MS tutorial (i.e. https://msdn.microsoft.com/en-gb/data/jj591621.aspx) version 1 creates tables for Schema v1:
Blogs table with two columns (BlogId and Name)
__MigrationHistory with one row (MigrationId contains InitialCreate). Not sure what this is about, but I guess it's the initial schema. Am I right?
Then I open Package Manager Console and I type: Enable-Migrations which creates classes for migration (201610091823367_InitialCreate.cs and Configuration.cs). I then modify the Blog class to have a new property Url as suggested in the tutorial and run Add-Migration AddBlogUrl, which creates 201610091830008_AddBlogUrl.cs
In addition, I added
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());
to the main, so when the application starts it should migrate automatically.
I launch the app v2, and everything is working perfectly. The Table has now the new column.
When I launch the app v2 again, it crashes with exception:
Unhandled exception: System.Data.SqlClient.SqlException: There is already an object named 'Blogs' in the database. and all the related stack trace.
So it looks like it's not recognizing that it's in the DB there's the most recent schema, so it tries to create the table again. I have added a breakpoint to InitialCreate class, method Up and it is called. I am surprised!
I've tried also a different approach:
ran app v1
ran app v2b with AutomaticMigrationsEnabled = true; in the Configuration class. The outcome is the same.
Can anyone help me to understand what's wrong and what's the right approach?
Can you confirm that in the meantime I am OK to deploy SCHEMA v1 without having enabled migrations at all?
I was hoping that this kind of scenarios were covered by Entity.

Related

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.

.NET Core EF 2.1 Scaffolding - DatabaseFirst - How to add more tables

I have a clean project solution (intended to be a .NET Core MVC app)
I have two projects - Home.CorePoC.EntityModel and Home.CorePoC.Model
I am calling dotnet cli from Home.CorePoC.Model.
The idea is that I want partial classes and logical separation from custom attributes and attributes from database.
I want to write a PowerShell script that I will be calling when I want to add/remove some tables, columns in tables etc.
In dotnet CLI when I add initially tables, it works just fine:
Scaffold-DbContext "Server=sqlServ2016;Database=TestDb;Persist Security
Info=False;User ID=admin;Password=admin;" Microsoft.EntityFrameworkCore.SqlServer
-Tables "Table1","Table2","Table3" -ContextDir "..\Home.CorePoC.EntityModel"
-OutputDir "TestDB" -force -DataAnnotations -UseDatabaseNames
Now, when I want to add just more tables it work as well but I have an error message: "Cannot add 'Table4'. There is already a linked file in this folder with the same name."
Also, I get error in cli console:
Exception calling "AddFromFile" with "1" argument(s): "A drag operation is already in progress (Exception from HRESULT: 0x80040103)"
Must I delete all files and then recreate it (linked file TestContext.cs that was initially created) or there is different way how to avoid this error message which is non-critical (I successfully added Table4 to my models).
I am planning to put this statement into PowerShell script which it will be called from project folder (where I have installed nuget Microsoft.EntityFrameworkCore.Tools(2.1.4))
That is because it will try and add the Context file for Table4 but is unable to as one already exists. There is already a feature request to update Entity Framework Core scaffolds rather than having to recreate them every time. You would have to override the generated entities each time by using the -Force flag

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.

Entity Framework 6: How do I reset a database using code first migrations and an FTP deploy

I deploy to a staging server that I don't have control over and have only been given FTP access. I've successfully used EF6 Code Migrations to create and seed the database on the staging server using the method described here.
I would like to basically do the equivalent of the following, but in code, when I deploy via FTP:
Update-database -TargetMigration:0
Update-database
My goal: I have new seed data to replace the existing data.
Any help is appreciated!
As usual I always figure it out moments after posting a question. (I promise I was looking for a long time before finally posting)
I did not realize you could pass a ConnectionString argument to Update-Database. So basically this was all I needed in the end:
Update-database -TargetMigration:0 -ConnectionString "MY_STAGING_CONNECTION_STRING" -ConnectionProviderName "System.Data.SqlClient"
And then on my next deploy it automatically migrated back to the latest version.

Entity Framework Enable-Migrations

All my searches are coming back to the same one of two issues, which aren't the problem in this project. I've never had trouble with this before, but this particular project is being weird.
First off, the project name is Site. The class SiteContext inherits DbContext.
When I run Enable-Migrations, even explicitly , the Package manager console returns an error:
PM> Enable-Migrations -ContextType SiteContext
The context type 'SiteContext' was not found in the assembly 'Site'.
But it's right there in the code:
// Not in a namespace or anything
public class SiteContext : DbContext {
// public DbSets in here
}
I can use SiteContext anywhere in my site's code, access the database though an object of it, etc. It's only the Enable-Migrations command that can't find it. Other than this, Entity's code-first functionality is working properly.
Any ideas what might be going on? Where did I mess this up?
(Entity Framework 6.0.2 / Web Pages 3.1.1)
ASP.NET Web Pages sites are built using the Web Site project type. This project type doesn't support Entity Framework Migrations. If you want to use Code First Migrations with an ASP.NET Web Pages site, you need to develop your data access code as a separate class library. That project type does support EF Migrations. I've blogged about it here: http://www.mikesdotnetting.com/Article/217/Code-First-Migrations-With-ASP.NET-Web-Pages-Sites
Instead of -ContextType, use -ProjectName and Specify Site.
Edit: First, try -ContextTypeName. I have to assume you didn't.

Categories