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.
Related
I'm creating WPF application using Entity Framework 6 with database first approach. EF did everything for me and i'm able to connect to the database and so far downloading data works, so connection exists. But every time i add user control it gives me new error that connection string was not detected. Program works fine anyway, but its hard to program when your error window is flooded with it.
I have found out that changing context from:
public MediaRentalEntities()
: base("name=MediaRentalEntities")
{
}
To this:
public MediaRentalEntities()
: base("MediaRentalEntities")
{
}
Should fix the issue, but it doesn't.
Now it throws exception (and shows this error multiple times, based how many user controls i have, currently 3):
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
This is my current app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="MediaRentalEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;data source=localhost;initial catalog=MediaRental;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
It's starting to be tiring, i'm tempted to change to EntityFrameworkCore or even Dapper, it feels like EntityFramework6 is against the user, but WPF has way more functionality on .NET Framework.
in connection string replace MyModel with "MediaRentalEntities" .It will work
Or
If you have generated it using DB first then you will already have context class where code is like
public MyModel()
: base("name=MyModel")
{
}
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.
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
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>
I have an EF 5.0 model that has been generated from the database. This model exists in a class library project. This class library project has an app.config file that contains the connection string information for the model.
Whenever I choose "Update model from database", I have to reenter the connection string. It doesn't seem to see the string from the app.config file.
Also, during the model update, if I click to save the connection string in the app.config, it never does.
Here 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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings>
<add name="mapEntities"
connectionString="metadata=res://*/mapModel.csdl|
res://*/mapModel.ssdl|
res://*/mapModel.msl;
provider=Oracle.DataAccess.Client
provider connection string=
"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=myserver.com)(PORT=1521)))(CONNECT_DATA=(SID=MYDB)));User Id=MYUSERNAME;Password=MYPASSWORD;""
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
How do I make EF see the connection string from the app.config? I need to add a function import to the model and I can't because it says that no connection has been configured for the model.
EDIT
Well I found a solution, abeit a hacky one.
See this stackoverflow post here.
The OP stated that he recreated a new EDMX file in the project, and that fixed it. I did the same, it did. I did not regenerate my old EDMX file. I just created a new one, and then went back to the old EDMX and it works now.
Copy the connectionString section to your web.config file.