EF Core Migration problem with updating a server - entity-framework-core

Locally my database works fine. I try to put a server database to the same version as my development version.
In Visual Studio, I ran this command:
dotnet ef migration scripts lasknown_script_that_was_executed_on_prod_server
where I use the value of
lasknown_script_that_was_executed_on_prod_server
as found on the production server by querying:
SELECT TOP 1000
[MigrationId], [ProductVersion]
FROM
[MyProject].[dbo].[__EFMigrationsHistory]
and yes it's in my source code as well, so seems OK, my code knows that version.
After I perform that command, it creates a large output but on top of that it shows an error
Build started...
Build succeeded.
Error writing app settings | Cannot perform runtime binding on a null reference
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.5 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.5' with options: > None
BEGIN TRANSACTION;
GO
CREATE TABLE [MyApplication] ( ...my firs db create..?? ...
I assume therefore the output code is missing something that should go before the very first initial database creation.
(as my prod server is not at that version, it shouldn't start with the first migration).
Locally it works fine, however, and it was set up with code-first.
So it was generated by code, it should migrate as well by code.

Related

Entity Framework Core: Script-Migration not recognizing migrations when creating script

I've got a full .NET Framework 4.6.2 Web API app that I've installed Entity Framework Core 1.1.2 into. It contains some classes, a DbContext class and has the relevant EF Core NuGet packages installed.
When I run Add-Migration Initial in the package manager console within Visual Studio, it correctly identifies the DbContext in the project and produces the migration class as well as a snapshot. The migration looks correct, given that within the Up method, it shows a number of create tables for each of the classes I want, it shows the expected columns for each and the constraints I'd expect, so that looks good. Also, within the Down method, it drops all the tables (which makes sense since this is the first migration done). This migration class is created in the /Migrations directory within the project.
When I run Script-Migration in the console next, it produces a SQL script that is incorrect, in that it only creates the table for the EFMigrationsHistory, as follows:
IF OBJECT_ID(N'__EFMigrationsHistory') IS NULL
BEGIN
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
END;
GO
This SQL file is created in the bin/Debug directory for the project.
I would expect that the output of this Script-Migrations command contain the SQL version of the Up method in the migration class that was produced by the previous Add-Migrations Initial command, but alas, this is not the case. If I run Update-Database, it runs against this SQL file and continues to ignore the existing Migrations.
Similarly, this appears to be a larger issue with EF Core, because if I attempt to do a Remove-Migration as suggested in the console after running Add-Migration, it is also unable to find the Migration it just produced and gives me the following error:
No ModelSnapshot was found.
And I know this can't be the case because I see it right there in the Migrations folder along with the initial migration class it created.
What's going on and is there any known workaround to get these tools working appropriately?
Update
While testing, I've found that if I create a new solution with just these few parts in it, it works fine. However, in my original solution, I have these projects within a number of solution folders, so perhaps that's the issue at hand, because putting the new project in a solution folder causes the same issues observed in the rest of this question.

How to cope with "No data stores are configured"?

I am currently playing with beta4 of EF7 using the blank ASP.NET web project template.
After having kicked off the existing migration, resulting in the tables being created in the localdb, the following occurs:
Strangely, when I clean up the migration-folder, including removing ApplicationDbContextModelSnapshot.cs and I run
dnx . ef migration add twice, I get the following error:
dnx : System.InvalidOperationException: No data stores are configured. Configure a data store by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
The second migration is not created. When I review the created migration it contains all tables whereas the database is already provisioned, so you should expect the migration being empty.
Then, when I remove the first migration and run the add migration command again more than once, all the migrations are correctly created, i.e. as empty files.
Can someone explain this to me? Is this expected behavior or is this a bug in beta4?
Tip for people coming from former EF-versions:
* Don't use the K command framework anymore.
* Don't use the Add-Migration cmdlets anymore.
Both have been replaced by dnx . (dot). (dnx = .NET execution environment)
Some references:
https://github.com/aspnet/EntityFramework/wiki/Entity-Framework-Design-Meeting-Notes---September-11,-2014
http://jameschambers.com/2015/05/project-k-dnvm-dnx-dnu-and-entity-framework-7-for-bonus-points/
Remove the constructor of ApplicationContext. It is a temporary workaround to enable deployment, but it interferes with the Migrations commands.

EF 6 Code First Migration - Controlling the sequence in which Migration scripts execute and DB schema gets created

This is my first question in SO, though i have been referring to questions posted for quite some time.
I was recently doing a code first migration for an existing database to migrate it to the latest version. My DB initializer was using the default strategy "CreateDatabaseIfNotExists" and I'm using SQL server 2012 express.
The following were the steps used to do the migration:
1. Enabled migrations with the older database v1 and corresponding code version cv1. Generated initial migration script with -IgnoreChanges option. Updated the database with this migration.
2. With the latest code version cv2, used the older database v1. Added migration to generate the actual migration script for the schema changes and updated database
This worked perfectly for an existing database and it got successfully migrated to the latest version.
But for a new database, the database gets created, but seeding was not happening. On debugging, I could notice that the migration scripts are getting executed first even before DB schema was created.
The migration scripts are failing since the tables being migrated have not even been added yet.
Note:
I have turned OFF AutomaticMigrationsEnabled for migrations.
Please note, a similar approach to the above was working fine for the earlier version of EF - 4.3 which i was using.
This is the code in App_Start:
Database.SetInitializer(new DBLayer.Models.MyDBInitializer());
using (MyDBContext db = new MyDBContext())
{
db.Database.Initialize(false);
if (!db.Database.Exists())
{
((IObjectContextAdapter)db).ObjectContext.CreateDatabase();
}
//Initializing membership APIs
MembershipInitializer.InstallServices();
In the above code, after db.Database.Initialize, migration scripts are executing where as tables are not yet added and hence error gets thrown.
On disabling migrations and creating a new database, things work fine again.
My questions are:
How can you control this sequence for executing migration scripts to first add the tables before executing migration scripts. What am I missing here?
When automatic migration is turned OFF which are the migration scripts getting executed first place?
Please advise. Please let me know if you need any more info.

UnintentionalCodeFirstException thrown by mstest

I have a test project which references another project, which in turn references a third project containing my Entity Framework 5.0 file (edmx). I find that I can run database-driven unit tests directly from Visual Studio, but when I run from mstest I get the following errors:
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException:
Code generated using the T4 templates for Database First and Model
First development may not work correctly if used in Code First mode.
To continue using Database First or Model First ensure that the Entity
Framework connection string is specified in the config file of
executing application.
I have non-database connecting unit tests which run fine. I've fiddled with my various app.config EF connection strings and they seem to be OK (every tests runs fine on Visual Studio). The problem is when I run mstest from a command line on my desktop or on a build server. This is the command I use:
MSTest.exe /nologo /searchpathroot:"\Binaries"
/resultsfileroot:"\TestResults"
/testcontainer:"\Binaries\driver.orderedtest"
/testcontainer:"\Binaries\EF.DataAccess.dll"
/publish:"http://"
/publishbuild:"vstfs:///Build/Build/99" /teamproject:"ProjectName"
/platform:"Any CPU" /flavor:"Debug" /noisolation /detail:errormessage
/detail:errorstacktrace /detail:stderr
I have references to all dll's in the test project, as outlined here: Entity Framework custom tool does not correctly embed or load the model as resource files
I've been on this for a few days off and on, and it looks to me that this is an EF 5.0 bug, but according to the connect link this should be fixed, but it doesn't seem to be the case.

add-migration does not function with remote sql server databases in shared hosting

It looks like CodeFirst stops doing its homework when it doesn't have full control of the database (I suppose).
The scenario is a web site hosted on Arvixe.com (or I suppose any other shared hosting server), where I have to create databases only from their control panel (and NOT with Sql Server Management Studio, just to say...).
Once created an empty database, I register a connection in the web site, and I use it to generate database from poco objects like in:
add-migration m1 -targetdatabase myconnection
This generates correctly my FIRST migration, that I can apply without problems with
update-database -targetdatabase myconnection
The first concern, not too important, is that since the database is existing, it will NOT issue the Seed command, so I have to insert my first records by hand, but this is not a great problem.
Then I change my poco objects, and I need to update the database, but when I issue ANOTHER
add-migration m2 -targetdatabase myconnection
it gives the error:
System.Data.Entity.Migrations.MigrationsPendingException: Unable to generate an explicit migration because the following explicit migrations are pending: [201111081426466_m1]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
This is really strange, since if I look at the database, I can see even the table __MigrationHistory, but then it looks like it cannot recognize it...
Anyone with the same problem, or some good tip to where investigate?
Thanks in advance,
Andrea Bioli
I had this problem. I was able to resolve it by providing a connectionString and a connectionProviderName parameter to both the Update-Database and the Add-Migration commands.
If you have many projects in your solution with multiple config files, Package Manager seems to be confused. In my case, I had one project selected as the default project for Package Manager Console, but it was pulling the connection string from the Visual Studio solution default start-up project instead.