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
Related
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
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 got a ASP.NET MVC 5 project which is already published in a server. But I have to extend it. Thus I'm trying to make local development environment with local database. I don't want to loss any data which is already working. As this is huge project. So all model and controller is done.
I'm also not an expert in ASP.NET world. After searching for a while I found there is way called code first approach.
As I have all the model so I'm assuming it should be able to make all local database in my machine.
The actual project connection strings looks like this:
<connectionStrings>
<clear />
<add name="Name.DataSourceConnectionString"
connectionString="Data Source=test.test.com;User ID=myUser;Password=myPass"
providerName="System.Data.SqlClient" />
</connectionStrings>
So for local machine I updated as:-
<connectionStrings>
<add name="My TEST"
connectionString="Data Source= 192.168.1.12;Initial Catalog=MyDB;Persist Security Info=True;User ID=dev;Password=dev"
providerName="System.Data.SqlClient" />
</connectionStrings>
I got project source and build and launch the service locally. When I try to logged in I get following error:-
The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Note that same login is working fine in server.
Then I follow the link.
In package management console I insert command enable-migrations and then update-database -Force. I got 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 have SQL Server 2012 Express installed. I suspect my connection string is not defined correctly. How do I define it? Also any suggestion how to have local set-up development environment for working ASP.NET service?
connectionString="Server=myip;Port=3306;Database=mydatabase;Uid=admin;Pwd=password;"
you could try this maybe you missing port and select database don't know how many database is configure in your mssql server.
Code First, despite its name, can either create a new database or work with an existing database. However, and this is key, it cannot both create and manage tables and work with existing tables in the same database (at least not with the same context).
You can have multiple contexts, but they must be entirely segregated, i.e. they can't reference entities tracked by a different context or they'll attempt to take control of those entities away from that other context.
Long and short, if you have an existing database that you need to work with, Code First migrations are pretty much out the window. You can create new entity types, but you'll need to create the tables for them manually in your database.
As far as just get a local copy goes, though, all you need to do is take a backup of the production DB and restore it locally. It really has nothing to do with Entity Framework or MVC.
We have three projects.
Company.Domain (class library)
Company.PublicWebsite (MVC3 Web Application)
Company.InternalWebsite (MVC3 Web Application)
The two website projects have reference to Company.Domain.
Our EF 5 DbContext lives in Company.Domain.Data.EntityFramework and it looks like this:
using System.Data.Entity;
using Company.Domain.Data.EntityFramework.Entities;
namespace Company.Domain.Data.EntityFramework.
{
public class CompanyEntities : DbContext
{
public DbSet<Notification> Notifications { get; set; }
public DbSet<Report> Reports { get; set; }
public DbSet<ReportSection> ReportSections { get; set; }
public DbSet<ReportPage> ReportPages { get; set; }
// brevity brevity
}
}
We have enabled migrations and successfully used the tool in the past so I'm not sure why we are having issues now. Our migrations configuration lives in Company.Domain.Data.EntityFramework.Migrations and looks like this:
namespace Company.Domain.Data.EntityFramework.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Company.Domain.Data.EntityFramework;
public class Configuration : DbMigrationsConfiguration<CompanyEntities>
{
public Configuration()
{
MigrationsDirectory = #"Data\EntityFramework\Migrations";
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CompanyEntities context)
{
// empty at the moment
}
}
}
We then have an App.config file in the root of the Company.Domain project and it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="CompanyEntities" providerName="System.Data.SqlClient" connectionString="Data Source=devsql;Initial Catalog=CompanyEntities;uid=XXXXX;pwd=XXXXX;MultipleActiveResultSets=True;" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Our database lives on another server on the network. I'm able to connect to it in SQL Server Management Studio and our applications are able to connect at runtime just fine. However, when I try to run add-migration or even update-database I get the following error:
http://content.screencast.com/users/Chevex/folders/Snagit/media/80fbfd6a-4956-407f-b88f-d5a53a9e5feb/03.21.2013-10.25.png
System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ---> System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: 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.
I've even reverted my changes to the model and then ran update-database just to see if it would say 'database is on latest migration' but I still got the above error. I've poured over the connection string in App.config over and over. I cannot figure out why migrations won't connect but both of our website projects work just fine at runtime. Migrations have worked in the past. Below are the migrations in solution explorer compared with those found in the __MigrationHistory table in the database.
http://content.screencast.com/users/Chevex/folders/Snagit/media/7abeaa46-ff0f-4817-a0d7-1adb086e8f0c/03.21.2013-10.30.png
http://content.screencast.com/users/Chevex/folders/Snagit/media/3c6ac54d-f63d-417f-9253-39b6a8fea85d/03.21.2013-10.32.png
It looks like I should be able to run update-database and have it tell me that it is up to date, but I get that error instead.
As I understand it, migrations shouldn't be paying any attention to our two website projects when I'm running migrations commands, but I poured over their Web.config files as well just in case. The connection strings are identical to App.config.
Edit:
I've even tried completely uninstalling and removing the EF 5 package from the projects and reinstalling. Same issue >:(
Did your start project contains web.config or app.config as EF use the start project as source of the connection string
OK, so that didn't work for me at first :(
Then after a cup of coffee and adding StartUPProjectName to it, it did!
Try:
Update-Database -StartUpProjectName MYPROJECT.NAME -Script
Try to point it to a start Up project where you web.config/app.config lives
If you get the help for enable migrations in the Package Manager Console
Get-Help enable-migrations -detailed
You can find this documentation for the -StartupProjectName option:
-StartUpProjectName
Specifies the configuration file to use for named connection strings. If
omitted, the specified project's configuration file is used.
The doc it's a little confusing, but it means that if you use this option to specify a project name, migrations will look for the connection string in the config file of the specified project. (The config file can be web.config or app.config).
If you're creating a web app, most probably the connection string will be in its web.config, so you have to specify the web app project. If it's other kind of project, the connection string will be in an app.config file of a class library or whatever, and you'll have to specify that project.
Besides it's recommended that you use a constructor for your DbContext class that specifies the name of the connection string, i.e.
public class CompanyEntities : DbContext
{
public CompanyEntities()
:base("ConnectionStringName")
{
...
}
....
}
In this way you don't depend on default connection strings, which may be confusing.
You say you can connect via SQL Management Studio, but my guess is you use Windows Authentication for that, and not the uid=XXXXX;pwd=XXXXX; supplied in your connection string.
Try to get Management Studio to connect using that userid and password.
Also, that account might be locked out (if it is an Active Directory account).
This sounds eerily like a problem a client of mine had. It had to do with something having mucked up the DbProviders section of machine.config. He put the details here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/f2a19487-6d38-4a79-a809-d3efe4c9d9fe (it's the Adam Scholz answer to his boss' question. :) )
Julie
May be this is solved already but i got it solved by setting the start up project in my solution to the entity dll project ( having app.config file ). I did set the "Default project" in Package Manager Console window to the correct entity dll project but that did't work. For details
Entity Framework 6 with SQL Server 2012 gives System.Data.Entity.Core.ProviderIncompatibleException
system-data-entity-core-providerin
If your solution has multiple projects, try setting the Startup Project for the solution to the project that contains the Web.Config or App.Config file that contains the settings for EF.
I had a solution with a Web project and seperate project (Data.Models) for my models. All was well until I added a console application to the solution. As soon as I set that to be the startup project, EF Migrations would fail.
Also, if multiple projects in the solution have migrations enabled, always run the Update-Database on each project after you do a Add-Migration. My web project had a pending migration, and the migrations failed weirdly on the second project because of the pending migration in the first.
I have created an initial migration with Add-Migration. When I run Update-Database on an empty DB it creates all tables, including adding an entry in the __MigrationHistory table.
Now I run Update-Database again just to test, and instead of "No changes detected" I get this:
PM> Update-Database -Verbose -Project testProject.Web
Using StartUp project 'testProject.Web'.
Target database is: 'testProject_dbo' (DataSource: localhost, Provider: Devart.Data.MySql, Origin: Explicit).
Applying explicit migrations: [201203151243164_Start].
Applying explicit migration: 201203151243164_Start.
CREATE TABLE attachments (
...table data...
)
Table 'attachments' already exists
Table 'attachments' already exists
It seems like the update is unaware of the current DB state. The only solution is to delete all tables and update. That works also if I add more migrations.
As you see, I am using a different database provider than usual (Devart.Data.Mysql), but I'm not sure if the problem is there. Maybe I'm missing something trivial?
The problem was resolved after communicating with DevArt. I never called the IgnoreSchemaName workaround in the Configuration class that was generated when running Enable-Migrations. To summarize, this is the class that made it work finally:
internal sealed class Configuration : DbMigrationsConfiguration<YourDbContext>
{
public Configuration()
{
// Because the Package Manager Console (NuGet) instantiates YourDbContext with the empty constructor,
// a custom connection must be specified. Based on http://www.devart.com/blogs/dotconnect/?p=5603
// Note that the MySqlProviderFactory must also be present in Web.config or App.config in the *startup project*
// for this to work! Configuration example:
/*
<system.data>
<DbProviderFactories>
<clear />
<remove invariant="Devart.Data.MySql" />
<add name="dotConnect for MySQL" invariant="Devart.Data.MySql" description="Devart dotConnect for MySQL" type="Devart.Data.MySql.MySqlProviderFactory, Devart.Data.MySql, Version=6.30.196.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
</DbProviderFactories>
</system.data>
*/
// Apply the IgnoreSchemaName workaround
MySqlEntityProviderConfig.Instance.Workarounds.IgnoreSchemaName = true;
// Create a custom connection to specify the database and set a SQL generator for MySql.
var connectionInfo = MySqlConnectionInfo.CreateConnection("<Your ConnectionString>");
TargetDatabase = connectionInfo;
SetSqlGenerator(connectionInfo.GetInvariantName(), new MySqlEntityMigrationSqlGenerator());
// Enable automatic migrations if you like
AutomaticMigrationsEnabled = false;
// There is some problem with referencing EntityFramework 4.3.1.0 for me, so another fix that needs
// to be applied in Web.config is this:
/*
<runtime>
<assemblyBinding>
<!-- This redirection is needed for EntityFramework Migrations through the Package Manager Console (NuGet) -->
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
<bindingRedirect oldVersion="4.3.0.0" newVersion="4.3.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
*/
// After these Web.config additions, running migrations in Package Manager Console should be as easy as:
// Update-Database -Verbose -ProjectName Your.MigrationsProject
// Creating new migrations:
// Add-Migration -Name MigrationDescription -ProjectName Your.MigrationsProject
}
}
After that I emptied the database one more time to generate a correct migration history entry, and everything was fine. DevArt gives more details about the configuration.
I had the same odd behaviour, but in my case it turned out to be much simpler: a code merge had reset my Startup Project to the default, which was not the project that contained the migrations.
I didn't notice until I tried the -Verbose flag, which explicitly laid out that my Startup project was not the same as the NuGet project configured in Package Manager.
Worth the sanity check!