i have an entity model contained in a dll and i am writing some unit tests for it. when i run it it says the connection string can't be found in the application config.
Data:
model:
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog" />
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<connectionStrings>
<add name="efContext"
connectionString="metadata=res://*/Models.efModel.csdl|res://*/Models.efModel.ssdl|res://*/Models.efModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Production;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
the connection string is clearly in there.
When my test calls a function within the dll which is written like this
Public Function Find(ByVal SectionId As Integer) As Data.Section Implements ISection.Find
Dim SectId As String = SectionId.ToString()
Using dataContext As efContext = New efContext()
dataContext.Database.Connection.ConnectionString = _efConnectionString
Dim c As Data.Section = Nothing
c = (From cs In dataContext.Sections
Where cs.SectionId = SectId).FirstOrDefault()
Return c
End Using
End Function
it fails on dataContext.Database.Connection.ConnectionString = _efConnectionString
although when i debug it it already has the exception.
I tried duplicating the app config in the unit test project. I tried linking the app config as a shortcut. I have been stuck on this for about a full day now. I have tried just about every solution i have seen on stack overflow. it just doesn't seem to work.
I have even tried remaking the entity model and that didn't help either.
Any ideas?
Related
I am trying to move my app.config ef settings to code.
<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 -->
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0"
type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0"
invariant="System.Data.SqlServerCe.4.0"
description=".NET Framework Data Provider for Microsoft SQL Server Compact"
type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
</configuration>
Currently all I was able to set is the defaultConnectionFactory:
public class SqlServerCompactConfiguration : DbConfiguration
{
public SqlServerCompactConfiguration()
{
SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"));
SetProviderFactory("System.Data.SqlServerCe.4.0", new System.Data.SqlServerCe.SqlCeProviderFactory());
SetProviderServices("System.Data.SqlServerCe.4.0", new System.Data.Entity.SqlServerCompact.SqlCeProviderServices());
SetProviderServices("System.Data.SqlClient", new System.Data.Entity.SqlServer.SqlProviderServices());
}
}
For the last 2 lines I am getting the following error:
'SqlCeProviderServices' does not contain a constructor that takes 0 arguments'
I got no idea what to add here... Intellisense is showing nothing an so is the class when I use GoToDefinition there is no constructor...
Usually such service classes are implemented as singletons.
For instance, SqlProviderServices class contains the following:
//
// Summary:
// The Singleton instance of the SqlProviderServices type.
public static SqlProviderServices Instance { get; }
I can't check now, but I'm pretty sure SqlProviderService class has something similar.
The exception that was thrown was
"“The invocation of the constructor on type 'TestWPF.MainWindow' that
matches the specified binding constraints threw an exception.”"
Which I have googled and found this and several like it. All of which say to add <startup useLegacyV2RuntimeActivationPolicy="true" /> to you configuration file.
I have a method called GetCustomers:
void GetCustomers()
{
var context = new ContactTestEntities();
var query = from c in context.ContactTs
select c;
Listbox.ItemsSource = query.ToList();
}
It will throws the exception when on var query = from c in context.Contacts select c;
my config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="True" />
<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>
<connectionStrings>
<add name="ContactTestEntities"
connectionString="metadata=res://*/ContactTest.csdl|res://*/ContactTest.ssdl|res://*/ContactTest.msl;provider=System.Data.SqlClient;
provider connection string="data source=SQL;
initial catalog=ContactTest;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>
</configuration>
please tell me if you see something incorrect here. thank you
Okay, after an hour of digging I figured out that there wasn't anything wrong with the code. The problem was that I didn't have the config file in the startup file. So that is the answer put your connection string into the startup file.
For integration testing purposes I'd like to manually create and open an EntityConnection in the test fixture set up. This fails with the following exception when calling the Open() method:
System.Data.ProviderIncompatibleException : A null was returned after calling the 'GetService' method on a store provider instance of type 'System.Data.SQLite.EF6.SQLiteProviderFactory'. The store provider might not be functioning correctly.
I'm using the same connection string which is also used when EF takes care about connection opening. If I run the same test suite with automatic connection handling by EF it works.
...
[TestFixtureSetUp]
public void FixtureSetUp()
{
// Setup database
// Setup data access
...
var ec = new EntityConnection([ConnectionString]);
ec.StoreConnection.Open(); --> WORKS!!
ec.Open(); -> Throws
}
...
The connection string looks like the following:
metadata=res://*/Test.TestModel.csdl|res://*/Test.TestModel.ssdl|res://*/Test.TestModel.msl;provider=System.Data.SQLite;provider connection string="data source=C:\Test\tmp4C80.tmp;read only=False;pooling=False;failifmissing=True;synchronous=Full;datetimekind=Utc;enlist=True;setdefaults=False;datetimeformat=ISO8601;journal mode=Off;cache size=4194304"
The app.config for the NUnit assembly is the following
<?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.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite"
type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<!-- Register protable database data providers -->
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite"
description=".Net Framework Data Provider for SQLite"
type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6, Version=1.0.94.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
</DbProviderFactories>
</system.data>
</configuration>
Beside NUnit for testing, I'm using Entity Framework 6.1.1 and System.Data.SQLite 1.0.94.0.
Edit: The strange thing is that opening the store connection of the provided entity connection manually works...
I found out that I used the EntityConnection from System.Data.Entity instead of the EntityFramework assembly.
Is it possible to split the configuration for an enterprise library block into multiple files?
For example: I have three assemblies and one hosting project. I want to store the entlib v6 Exception Handling Application Block (EHAB) configuration for each assembly in a separate config file located in the particular assembly.
The hosting project references the three assemblies:
assembly_X
ehabX.config
assembly_Y
ehabY.config
assembly_Z
ehabZ.config
Hosting project
using ehabX.config
using ehabY.config
using ehabZ.config
I already tried the following:
App.config in the hosting project:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common" requirePermission="true" />
</configSections>
<enterpriseLibrary.ConfigurationSource>
<sources>
<add name="ehabX" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="ExceptionHandling\ehabX.config" />
<add name="ehabY" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="ExceptionHandling\ehabY.config" />
<add name="ehabZ" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="ExceptionHandling\ehabZ.config" />
</sources>
<redirectSections>
<add sourceName="ehabX" name="exceptionHandling" />
<add sourceName="ehabY" name="exceptionHandling" />
<add sourceName="ehabZ" name="exceptionHandling" />
</redirectSections>
</enterpriseLibrary.ConfigurationSource>
</configuration>
ehabX.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"/>
</configSections>
<exceptionHandling>
<exceptionPolicies>
<add name="Swallow NotImplementedException">
<exceptionTypes>
<add type="System.NotImplementedException, mscorlib" postHandlingAction="None" name="NotImplementedException"/>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
ehabY.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"/>
</configSections>
<exceptionHandling>
<exceptionPolicies>
<add name="Swallow ArgumentException">
<exceptionTypes>
<add type="System.ArgumentException, mscorlib" postHandlingAction="None" name="NotImplementedException"/>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
The ehabZ.config is omitted.
Using the EHAB with the policy "Swallow NotImplementedException" works fine. But if I try to use the policy "Swallow ArgumentException" defnied in ehabY.config I get this error message:
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException: The policy with name 'Swallow ArgumentException' cannot be found. Exception handling aborted.
Any suggestions?
Unfortunately, there is nothing out of the box that will let you merge multiple configuration sources into one configuration set.
I think you can probably do what you want but you will have to do some coding. You'll need to read in the appropriate configuration sources and create a custom IConfigurationSource that will merge them all. Additive merge of different config sources? has an example of a MergeConfigurationSource that could help you.
I need help configuring my WCF service that access a SQL database through EF. The service runs fine when I launch it locally through visual studio, but when I deploy it to another server and access it through my client application I keep getting "{"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."}" error.
My Connection string before I publish the service to the server is:
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
</entityFramework>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-ECUWebUi-20121116095239;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-ECUWebUi-20121116095239.mdf" />
</connectionStrings>
My Connection string after I publish:
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost; Integrated Security=SSPI; Initial Catalog=ECUWeb-Staging;User ID=user;Password=password" />
</connectionStrings>
This is the call to the EF context in the service:
public RegisterResponse Register(RegisterRequest request)
{
EfDataAccessFactory factory = new EfDataAccessFactory(new DtoMapper());
RegisterResponse response = new RegisterResponse();
if (request.Computer.Exists())
{
factory.ComputerDataAccess.Update(request.Computer);
response.Message = string.Format("{0} is already registered.", request.Computer.Name);
}
else
{
request.Computer = factory.ComputerDataAccess.Insert(request.Computer);
response.Message = string.Format("{0} registered with id: {1}", request.Computer.Name, request.Computer.Id);
}
RegisterInstances(request);
return response;
}
Any suggestions? Also the Inner Exception is null.
Fixed it I had to add:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=ECUWeb-Staging;User Id = user; Password = password" />
<add name="EcuWeb.Data.EcuWebDataContext" connectionString="Data Source=localhost;Initial Catalog=ECUWeb-Staging; User Id = user; Password = password" providerName="System.Data.SqlClient" />
Then it worked no problem.