I'm working on a project with different implementations of DbContext. Using EF code first, I generate migration :
Enable-Migrations -ContextTypeName <> -Force
Add-Migration <>_DB_v1.0
Update-Database -Verbose
The update always tries to attach the *.mdf file but no file is ever genrated in local, and I'm working on a distant SQL Server (Distant virtual DB)
the Update-Script option successfully generates the SQL file and well executed on the Db, but I always get error to execute last update before going on new migration.
Could any body help ?
Project is in .net 4.6, and using EF 6.0.
Sorry not able to paste code for confidentiality. I may ensure that All connection string, project conf. and so are perfectly set.
Please ensure that migration history table in the Db and Migrations files in your Solution are match.
I think you miss some migration.
I found the error reason:
1- Indicate explicitly the providerName="System.Data.SqlClient" in the connectionStrings definition
2- Executing the migration, specify the -ConnectionStringName, even if the name displaed in the console seems to be OK.
Add-Migration DB_vX.x -ConnectionStringName XXX_Database
update-database -Verbose -Script -ConnectionStringName XXX_Database
Related
Add-Migration : A parameter cannot be found that matches parameter name 'Context'.
At line:1 char:15
+ Add-Migration -Context ManagementSystemContext
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Add-Migration], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Add-Migration
I'm trying to add migration to App but I got this error despite using this command:
PM> Add-Migration -Context ManagementSystemContext
I uninstalled EntityFrameWork.tools then reinstalled it and restarted visual studio and still the same error
I had the same problem and I couldn't realize what it is. After 2-3 restarts of the PC and the VS, making the same command
Add-Migration NameOfTheMigration -Context MyContext
it appear something in the lines of
"if you are using EntityFramework or EntityFrameworkCore, make sure that you type EntityFramework\Add-Migration, or EntityFrameworkCore\Add-Migration".
I did that and the migration was on.
So the command line looked like this:
EntityFrameworkCore\Add-Migration NameOfTheMigration -Context MyContext
I'm guessing that there were both, EF and EFCore, so the PMC was confused.
Anyway, this is what worked for me.
After "Add-Migration" command EF first expects the name of the migration.
You can cheek this documentation and code sample to see if you did something wrong.
Also you can try to do it via .net core CLI instead of Package-Manager Console, like:
dotnet ef migrations add MigrationName --context ManagementSystemContext --output-dir Dir
Hope something will help.
If your project has two contexts as well as Multi Startup. You must do the following steps:
1- First, take the project out of Multi StartUp mode and set the project startup to your desired Startup.
Then in the Package Manger Console section, type the following command:
Add-Migration -Context ContextName
NOTE : Your default Project in package manger console must set as your DataAccess class libarary
I encountered some weird behaviour with EF Core 3.1 that made me wondering what is actually happening. So hopefully someone can explain this to me in all fine details.
Scenario
Let's say you have two projects. Project A (main) and project B (side-project). For both projects you can add/remove migrations, as project A is set-up to get all pending migrations from project B on start-up and execute them.
When executingdotnet ef migrations add Test -c AppDbContext -o DbContexts/Migrations/AppDb on project A and after completion (BEFORE even applying it to the DB) execute dotnet ef migrations remove -c AppDbContext, everything works as expected and the migration gets removed.
For project B on the otherhand after succesfully executing the add command, the moment that I try to execute the remove command (also BEFORE even applying it to the DB), I get the following error:
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related
or instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify
that the instance name is correct and that SQL Server is configured to
allow remote connections. (provider: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server)
So I took the error message as an advice and started to follow this guide to allow remote access to the database. After the guide, the remove command on project B was also successfully executed.
But now I am wondering... Why wasn't EF Core connecting to the (LOCAL) DB before I followed the guide and DID it work on project A, but not on B....?
EDIT
After some more research, I discovered the specific action from the guide that helped me to resolve the error that I got. It was to set the TCP Port to 1433 in the Sql Server Configuration Manager. Apparently this field was empty... But it leaves me with 1 question.
Why did the add command DID work without a port specified and was only the remove command complaining about the connection?
EDIT2
And yet another new finding, when adding the following method to the AppDbContext class:
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("foo");
base.OnConfiguring(options);
}
The add command works fine, but the remove command complains about the incorrect format of the connectionstring
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
So we can conclude from this that the add command DOESN'T require a valid connectionstring (as it does nothing with the DB), while the remove command DOES require a valid connectionstring... but why??? It does nothing with the DB, right?
As an answer to my own question, here an explanation on how the add and remove migrations work.
The add migration functionality DOES require a valid string as the connectionstring in the context, but it DOESN'T need to be a correct connectionstring, as EF Core is not realy connecting to the DB.
For the remove migration functionality, you DO require a correct connectionstring, as EF Core makes a connection to the DB to compare the local list of migrations with the _EFMigrationsHistory table to check if there are any migrations that has not been applied to the DB. Because the remove functionality can only remove PENDING migrations. So not any migrations that have already been applied to the DB.
Let's say I have migrations
Initial.cs
foo.cs
bar.cs
baz.cs
and my database is current "in sync" with applying
Initial.cs
foo.cs
and what I want to do is the equivalent of
Try applying bar.cs and then baz.cs, all in a transaction. If it fails, roll back.
Is that possible using Update-Database or migrate.exe with parameters or does it request special Powershell script or even custom C# logic?
I don't think this is possible, but you can easily revert to a previous migration as EF allows that:
Update-Database -TargetMigration "PreviousMigrationIdentifer"
-ConnectionProviderName "System.Data.SqlClient" -Force
You can even use a connection switch to do that on Dbs having issues with migrations applied:
-ConnectionString "Data Source=(LocalDB)\Tests;Initial Catalog=DnbName;..."
I'm switching from a MySql database to a Sql Server database.
I remove all related data to mysql from configuration and web.config.
But I still get this issue on Update-Database command in Package manager console:
Update-Database -Verbose
Using StartUp project 'B2Peer.Web'.
Using NuGet project 'B2Peer.EntityFramework'.
Specify the '-Verbose' flag to view the SQL statements being applied to the
target database.
Target database is: 'b2peer' (DataSource: .\SQLLOCAL, Provider:
System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
System.Data.Entity.Core.MetadataException: Schema specified is not valid.
Errors:
(0,0) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
I cleaned the solution and rebuild
Is there any cache files that I can clean to avoid EF to look for a provider Mysql ?
Note: I searched with notepad++ in all files in my solution folder and there are nothing related to my search 'mysql' ... So why EF still looking for this provider ...
Finally It was fixed.
After multiple clean, build, launch website with automatic migration to true.
Then Update-Database has stopped to give this error...
I have build an application with Entity Framework 6, created some methods to insert an extract data from a database, and I would now like to test it for both a production- and a debugging environment.
To be sure it all works as I would like it to, the debugging database should erase all data for my tests, while my production should keep its data.
I have two projects: MyApp.Database and MyApp.Database.Test, and they each have a connection-string in their app.config-file, which the program loads as so:
public DatabaseContext() : base("name=MyDB")
{
System.Data.Entity.Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
}
and connection-string, where the database parameter set to MyProdDB and MyTestDB:
<connectionStrings>
<add name="MyDB" connectionString="Host=localhost;user id=myUser;password=myPassword;database=MyProdDB" providerName="Npgsql" />
</connectionStrings>
When I run the application, and run the tests, I get the correct connection-string for each type of database.
But I get an error when I run my tests:
42P01: relation "dbo.Tags" does not exist. A simple message, saying I have not migrated my data into my test database.
But how do I migrate it into the test database?
I tried selecting the test-project in the Package manager Console, and running the following commands:
PM> Add-Migration "Init"
No migrations configuration type was found in the assembly 'MyApp.Database.Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No migrations configuration type was found in the assembly 'MyApp.Database.Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
PM> Enable-Migrations
No context type was found in the assembly 'MyApp.Database.Test'.
Do I need to specify my own DbContext class for MyApp.Database.Test which is almost a replica of MyApp.Database?
If you don't need data in your DEV environment, just drop database. You use CreateDatabaseIfNotExists, so it will create new database with up-to-date schema.
More then it, you can configure your initializer in config file. Use CreateDatabaseIfNotExists inializer on PROD and DropCreateDatabaseIfModelChanges on DEV. So if model will change, you will have to use migrations on PROD, but DEV will just drop database and create again.
Example:
<contexts>
<context type="Elmah.SqlServer.EFInitializer.ElmahContext, Elmah.SqlServer.EFInitializer">
<databaseInitializer type="Elmah.SqlServer.EFInitializer.ElmahDatabaseInitializer, Elmah.SqlServer.EFInitializer" />
</context>
</contexts>
or look here