EF 6 Update-Database failed with provider - c#

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...

Related

EF Core understanding migrations

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.

error 0152: Make sure the provider is registered in the 'entityFramework' section of the application config file

I am trying to run a test project, to debug the code, but the moment its trying to save data to a table in database its giving this error:
Schema specified is not valid. Errors: MSLEntities.ssdl(2,2) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file.
Made sure that both are using the same version of EF (6.0). Check.
Tried to enter the provider name in the connection string but
already using providerName="System.Data.EntityClient"
Tried removing and reinstalling EF using PM console. Check. Manually
removed Ef references and readded them. Check.
What am I missing?

Cannot attach the file '<>.mdf' as database '<>'

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

Connecting database to .net core MVC project

It is my first time using .NET core 2.2 and MySQL workbench ,
I am trying to build a very basic website.
I followed the following Microsoft tutorial
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-2.2&tabs=visual-studio
After I added a Scaffolded item,I followed the instructions and opened the NuGet package manager and executed these commands in the cli:
Add-Migration Initial
Update-Database
The Update-Database command raised the following error :
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)
I am working with a Bluehost (Shared Host) server, I modified the permissions so I could connect remotely to the database (and indeed I am connected through MySQL workbench)
I tried changing the ConnectionString to the following:
"ConnectionStrings":
{
"Piano3Context": "Server=162.241.*.*;Database=PianoDB;User Id=omyUsrName;password=myPass;Trusted_Connection=True;MultipleActiveResultSets=true;"
}
and yet I receive the same error.
If any other code will help please note and I will post.
The tutorial you mentioned is using and SQL-Server. For connecting to a MySql server you need a different database provider. You can install the Pomelo.EntityFrameworkCore.MySql nuget package for Mysql. See the providers page in the microsoft docs.
After that you need to change the options.UseSqlServer from the tutorial to options.UseMySql as described on the mysql providers project page.
In addition, this is how to set the options for MySQL, you can move the config string to the Configuration and use the GetConnectionString method.
services.AddDbContextPool<MvcMovieContext>(
options => options.UseMySql("Server=localhost;Database=ef;User=root;Password=123456;",
mySqlOptions =>
{
mySqlOptions.ServerVersion(new Version(5, 7, 17), ServerType.MySql); // replace with your Server Version and Type
}
));
I was beaten to it by #philipp-grathwohl you need to use MySql and configure that in your startup like his answer says.
You could use this command instead which Scaffolds the DBContext and Generates the EF models and Context in one command after you have changed the startup and added the nuget package Pomelo.EntityFrameworkCore.MySql:
Scaffold-DbContext "Server=<ip>;Initial Catalog=PianoDB;Persist Security Info=False;User ID=<username>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -context Piano3Context -force
Do let me know if this last command spits out any errors.

Two identical generated databases with Entity Framework 6

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

Categories

Resources