Code First can't enable migrations - c#

I'm trying to enable migrations but it's throwing an exception:
Checking if the context targets an existing database...
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: The 'name' attribute must be specified on the 'section' tag.
I'm assuming that the App.config file is not correctly set up (it was automatically set up when I added EF package). All I did was add the connection string:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section Name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.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="MyContext" connectionString="data source=MYSERVER;initial catalog=CodeFirstTest;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I'm using SQL Server 2008 R2.
As I do have a connection string, I don't believe I need the defaultconnectionfactory. Am I correct? (Note: Even without this section I'm still getting the same exception)
What else am I missing?

I had the same issue when my <connectionString /> entry is on top part of the Web.config, Right after <configuration>. Then I tried moving it right before </configuration>, and it worked.

This is mainly to do with the config file. So the actual stack trace that helps is "System.Configuration.ConfigurationErrorsException".
There can be many reasons but they all majorly include the correction in the config file as answered earlier.
Couple of possibilities which are little different than this are given below (But the stack really tells us)
One possible out of the way reason can be that, your project where the migrations are getting enabled can be different from the startup project. So be sure to add -StartUpProject to your nuget commmand.
Version of the entity framework used can be different in case of two different projects.

I met with the same issue. My problem is that there are double connection string on the Web.config file. like as below:
<add name="DB1234" ..../>
<add name="DB1234" ..../>
So we have to check our web.config file first!
Good Luck!

check the spelling of your 'connectionString' and make sure it is 'connectionStrings' I omitted the 's' before in my own case.
After adding the 's', that solved it.

In my case I had several projects in the solution and another project was set as the StartUp project. Setting the project that I was trying to enable migrations for as the StartUp project resolved it.

In my case, using DevExpress MVC generated template, it need to add extra lines after <sectionGroup name="devExpress">...<sectionGroup/> in web.config
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

in my experiences, for example is that all the information that is used to establish a connection with the database is the one that comes from the config file that is in the startup-project, and not the one that is in the project where i am generating or using the enable-migrations or update-database instructions, example i have project PRINCIPAL and another project DATA,i use the DATA project as my default-project only when running the packages in Packager console Manager, but the config file that really use is the one in PRINCIPAL.

Include this into <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
In my case this line is omitted when I have 2 instances of Visual Studio open.
Close all instances of the Visual Studio, open and reinstall EF via interface Nuget or Console to avoid this error

Check the webconfig, For example: I had the app settings like this:
<configuration>
<appSettings>
<add key="dhx_license" value="value"/>
</appSetting>
.....
and threw that error. But then I realized appSetting was duplicated below so I moved the and the error vanished. Thanks.

Like #Lester answer check web config. It must look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
...
<configuration>

I had the same issue. But I found there are two <connectionString /> in my Web.config,
I had to remove one connection string and it work fine for me.

Related

A solution that uses EntityFramework source projects instead its assemblies, could not start successfully

I have a WinForms project that uses EntityFramework 6.1.2-beta with .NET4, it worked fine, till I decided to replace EF assemblies with their source codes, for some tracing goals, so I removed EntityFramework.dll and EntityFramework.SqlServer.dll from my project references and get their source codes from CodePlex and add them to my solution.
I changed these new project configuration to DebugNet40(because my project works with .NET 4, but EntityFramework and EntityFramework.SqlServer projects work with .NET 4.5).
It compile successfully, but now when I want to run my project I get following error:
An unhandled exception of type 'System.IO.FileLoadException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
Additional information: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)
It is my app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices,
EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="ERPContext"
connectionString="Data Source=.;Initial Catalog=MyDb;
Persist Security Info=True;User ID=sa;password=*****"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I removed PublicKeyToken=b77a5c561934e089" from app.config too, but the problem exists yet.
Is there any Idea?
The Entity Framework source code is configured to produce delay-signed assemblies (which means they're marked as "should be signed in the future with the official key"). The official instructions at Entity Framework's GitHub page show how to disable strong name validation (run the EnableSkipStrongNames task: build /t:EnableSkipStrongNames), so that you can use the delay-signed assemblies without anyone having to release their private key. This is sufficient for development systems.
If you intend to release a product relying on your custom-built modified Entity Framework DLLs, you should generate a new key, and modify the EF source code to use that new key.
You can right click the project in Visual Studio solution explorer, and Signing on the left and uncheck sign assembly. In your web config you will also need to remove the public key token.

EF6.0 Code First - Change connection

After developing EF codefirst application locally,
I copied the database from localdb with generate scripts and create a new one at azure.
I added connection string to config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Server=tcp:XXXXXXX.database.windows.net,1433;Database=XXXXXX;User ID=XXXXXXXXXXX;Password=XXXX;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
When I try to call an object, I get this exception:
"Invalid object name 'dbo.Banner'."
DB connection is correct. I can connect with SQL Server Management Studio.
What is wrong with this code?
Does the manually creating DB cause the problem?
This problem happen specially when you are restoring database to another server and if you have changed the databse username.
To solve this problem the best way is to change all SCHEMA to dbo.
To change SCHEMA execute following code through your MSSQL Enterpeise manager
ALTER SCHEMA dbo TRANSFER oldSchema.TableName
It seems that the tables has not been created.
Some pointers:
Did you enable Automatic Migration?
AutomaticMigrationsEnabled = true;
You maybe prefer doing a manual update/creation?
In that case, select a project containing the configuration that points to your Azure DB and in the Package Manager console:
update-database
Or you can do it in code as well using the MigrateDatabaseToLatestVersion initializer class.
Here are some additional information for reference:
- MSDN: Code First Migrations
- ASP.NET: Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application

Issues with Web.config

I am trying to deploy an MVC app to an EC2 instance using Web Deploy, and everything is working until I try to run the application. I get the following error:
Parser Error Message: An error occurred creating the configuration section handler for entityFramework: Configuration for DbContext type 'Project.Modules.AppDbContext, Project' is specified multiple times in the application configuration. Each context can only be configured once.
I have looked all of the related issues I could find (error There is a duplicate 'entityFramework' section defined, There is a duplicate 'entityFramework' section defined - EntityFramework6 upgrade, The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception, The provider for invariant name System.Data.SqlClient is specified multiple times). It is an MVC app so there are multiple Web.config files, but the EF section it is complaining about doesn't exist in both places. Here are the relevant portions of my config file:
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
--------more config settings here---------
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=MYIP;Initial Catalog=db;Persist Security Info=True;User ID=user;Password=password" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
I have heard anything from it should be resolved in 6.1.0 to many other things. If I remove the entry from the configSection it gives me another error about how it can't find the right resources. The only other thing that might be worth noting is that if I deploy and un-check 'Execute Code First Migrations' it just times out instead of giving me the above error.
Check web.config in root or parent folders of your app's virtual directory. The duplicate section error happens due to web.config inheritance.
wwwroot
|-- web.config <-- ensure this doesn't have any connection strings
|-- your app
|-- web.config <-- inherites wwwroot\web.config's settings
As vcsjones states in their answer here
The Problem is in your parent directory.Even if you specified one,there is already one in .config file.

How to consume an Entity Framewok (v6) Library?

I can make an entity framework console application that displays the customers in the Northwind database.
However, when I try to create the Northwind Entity Framework in a separate class library that is consumed by a simple C# console application in a separate sub-project, I encounter some problems.
I read http://www.dotnetcurry.com/showarticle.aspx?ID=617
and watched http://msdn.microsoft.com/en-us/data/ff628208.aspx and followed the directions by copying the connection string in the app.config from the library to the console mode program directory and adding a reference to my northwind EF class library.
I'm still getting this exception when trying to create the dbcontext variable in my console program:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
After some more google searching I tried adding this code:
public abstract class BaseDomainContext : System.Data.Entity.DbContext{
static BaseDomainContext() {
var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
}
}
The problem now is I get the red squiggly line underneath "SqlServer" -- apparently there is no such namespace in my copy of System.Data.Entry. I just upgraded to EF 6 with nuget.
Can anyone help me resolve this?
Thanks
Siegfried
Sun Mar 30 2014:
Forgot to mention: I'm using Visual Studio 2013 on Windows 8.1. Here is my app.config from my console mode demo program, most of which was copied from the class library app.config. Now that I think about it, who is looking for that connection string? Is it the class library or my console mode demo program? What should be the name of the connection string?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.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="NorthwindEntitiesLib" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=KM;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Mon Mar 31 2014:
Everything works fine for VS 2012. I just add the reference to the class library, cut and paste most of the App.config file from the library app.config to the console mode app.config and everything works. What can we conclude from this? Looks like there is a bug in VS2013 with EF 6. Can anyone help me workaround this bug?
Ben: I tried your suggestions and, judging by your XML you posted, it looks like you are using EF 5. I just upgraded to 6. I'm still getting the same errors in VS 2013.
It is in System.Data.dll i.e. System.Data.SqlClient.
Make sure you have a reference to this.
Can you post your connection string?
This one works for me - I just created a new project and added a new .edmx file to the project and called:
using (YourDbContext db = new YourDbContext(){///}
This calls the parameterless constructor for the context which uses the default connection string setting from you app.config. Take a look at the constructor yourself to see what is auto-generated and you'll see what connection string is being used.
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="NorthwindEntitiesLib" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=KM;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>

EF 4.3+ How to get current database initialzer

How can I get the current database initializer, so I can test that the right one is set before automatic publish?
Edit: I want to create a test case that is testing if a team member forgot to remove a line like this:
Database.SetInitializer<SomeModel>(new DropCreateDatabaseAlways<SomeModel>());
but there is no method or property like Database.GetInitializer().
is there a way to get current database initializer?
I think you are going about this wrong, if you're relying on developers to remember to commit or not to commit a line.
You should consider decoupling the initialization from the code by setting it in the web.config or app.config. Using web.config transformations or SlowCheetah for app.config, you would have a transformation per configuration, e.g. Debug, Test, Production.
In the Web.Debug.Config, you would then specify which initializer to use for that configuration:
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<contexts>
<context type="Company.Product.Infrastructure.BoundedContext, Company.Product.Infrastructure" disableDatabaseInitialization="false" xdt:Transform="Replace">
<databaseInitializer type="Company.Product.Infrastructure.DatabaseInitializers.DebugDatabaseInitializer, Company.Product.Infrastructure" />
</context>
</contexts>
</entityFramework>
For the other configurations, you would replace the //entityFramework/contexts/context/databaseInitializer/#type in the above configuration to use another database initializer. This would allow you to use DropCreateDatabaseAlways for Debug, DropCreateDatabaseIfModelChanges for Test and disable initialization for Production.
As a test, I tried adding database initialization both in the code and in the .config and the .config takes precedence.

Categories