WCF EntityFrameWork Exception in IIS - c#

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.

Related

SQLite & Entity Framework 6 "The underlying data provider failed to open"

When my Winforms application reaches the first Entity Framework data "request" I get the following error.
Message: The underlying provider failed to open.
InnerException: Data source cannot be empty.
My connection string is being built dynamically to cater for the user's %appdata% directory path. I am building it at first runtime and updating the app.config with the connection string once it is built. The code that handles this is below:
public void ConstructEntityFrameworkConnectionString(string dbFileName)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.ConnectionStrings.ConnectionStrings["RemManagerDBEntities"] == null)
{
// Specify the provider name, server and database.
var provider = "System.Data.SQLite.EF6";
var providerName = "System.Data.EntityClient";
var attacheddbfilename = dbFileName;
// Initialize the connection string builder for the underlying provider.
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder {
AttachDBFilename = attacheddbfilename,
IntegratedSecurity = true,
MultipleActiveResultSets = true,
ConnectTimeout = 30,
ApplicationName = "RemManagerDBEntities"
};
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder {
Provider = provider,
ProviderConnectionString = providerString,
Metadata = #"res://*/EntityFramework.RemManagerDBModel.csdl|res://*/EntityFramework.RemManagerDBModel.ssdl|res://*/EntityFramework.RemManagerDBModel.msl"
};
var cs = new ConnectionStringSettings("RemManagerDBEntities", entityBuilder.ConnectionString, providerName);
if (config.ConnectionStrings.ConnectionStrings["RemManagerDBEntities"] == null)
{
config.ConnectionStrings.ConnectionStrings.Add(cs);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
}
An example connection string that it creates:
metadata=res://*/EntityFramework.RemManagerDBModel.csdl|res://*/EntityFramework.RemManagerDBModel.ssdl|res://*/EntityFramework.RemManagerDBModel.msl; provider=System.Data.SQLite.EF6; provider connection string="AttachDbFilename=C:\Users\MacbookPro\AppData\Roaming\RemManager\Datasource\RemManagerDB.db; Integrated Security=True; MultipleActiveResultSets=True; Connect Timeout=30; Application Name=RemManagerDBEntities"
The method is called as part of the main method in the program.cs file.
static void Main()
{
var conController = new ConnectionController();
conController.ConstructEntityFrameworkConnectionString($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\RemManager\\Datasource\\RemManagerDB.db");
// Start the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new RemManager());
}
I've got the following NuGet packages installed:
Entity Framework 6
System.Data.SQLite
System.Data.SQLite.EF6
System.Data.SQLite.Core
System.Data.SQLite.Linq
Initially I have based the setup procedure from the following site with an amendment made by the second link shown.
https://www.codeproject.com/Tips/1056400/Setting-up-SQLite-and-Entity-Framework-Code-First
https://github.com/ErikEJ/SqlCeToolbox/wiki/EF6-workflow-with-SQLite-DDEX-provider
Below is an example of the calls that I am making to the database via entity framework. When stepping through the code the exception begins on the db.tblGroups.Select line.
public class GroupController : IGroup
{
public List<tblGroup> SelectAllGroups()
{
using (var db = new RemManagerDBEntities())
{
return db.tblGroups.Select(g => g).ToList();
}
}
...
}
The final piece of the puzzle is the app.config. The current config is shown below.
<?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>
<!-- See Datasource.ConnectionController for the connection string builder.-->
</connectionStrings>
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<appSettings>
<add key="databaseFilePath" value="" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
</configuration>
For what else it is worth, entity framework is working from a database first configuration. I am also running Entity Framework 6.2 and SQLite 1.0.106.0.
I've tried my best to find a valid solution on other sites that caters for the fact that I am combining Entity Framework and SQLite, but I haven't been able to come up with much. When I take the SQLite out of the equation, I still haven't been able to come up with much. One of the better questions I had found was here, but I am already doing what the suggested answer recommends.
I had a similar problem earlier, except with localdb. The application has been working previously on the localdb, however this issue has started since I have been endeavouring toward making the application more self contained and user friendly (e.g. not needing to modify the exe.config manually once installed).
Any suggestions would be greatly appreciated.
You cannot use a SqlConnectionStringBuilder with SQLite, use SQLiteConnectionStringBuilder instead, and set the DataSource property to the database file name

Exception thrown while defining a query and connecting to Entity Framwork

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.

MySql EF6 with IdentityDbContext

I try to use MS Identity with an MySql Databse and Code-First.
My DbContext Class:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class TestDbContext : IdentityDbContext<ApplicationUser>
{
public TestDbContext()
{
}
public TestDbContext(string cnString)
: base(cnString)
{
}
}
My App Config:
<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>
<connectionStrings>
<add name="TestDbContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=test;uid=root;password=root"/>
</connectionStrings>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
</defaultConnectionFactory>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
If i use the normal DbContext its works with Code-First Migrations. But if i change to IdentityDbContext and i try to "Update-Database" i get the following Error:
Failed to set Database.DefaultConnectionFactory to an instance of the
'System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework' type as specified in the application configuration.
See inner exception for details.
How can i get MS Identity to work with MySql?
Ok i have change the DefaultConnectionFactory to
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
but now i get another Error:
Format of the initialization string does not conform to specification starting at index 0.
Ok i get the Database Connection to work but the Identity Tables such as aspnetuser won't create automaticly.

Entity model can't find the connection string in app config.

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?

How to integrate SQL Server CE with Enterprise Library 5 DatabaseFactory?

I'm getting an
"Activation error occured while trying to get instance of type
Database, key "" "
exception with my DatabaseFactory.CreateDatabase() whenever I reference the default database to a SQL Server CE
I tried checking if the problem is just my .dll reference, which I was able to prove wrong because I was still able to connect to a real SQL Server 2008 db.
Here's my config:
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false"/>
</configSections>
<dataConfiguration defaultDatabase="sqlCEDB"/>
<connectionStrings>
<add name="sqlCEDB"
connectionString="Data Source=|DataDirectory|\sqlCEDB.sdf;Password='somepassword'"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
Here's how I create the database instance:
private Database db;
protected internal Database DB
{
get
{
if (db == null)
db = DatabaseFactory.CreateDatabase();
return db;
}
}
SOLUTION
change config property
solved: providerName="System.Data.SqlServerCe.3.5"
SOLUTION
change config property solved: providerName="System.Data.SqlServerCe.3.5"
<configSections>
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false"/>
</configSections>
<dataConfiguration defaultDatabase="sqlCEDB"/>
<connectionStrings>
<add name="sqlCEDB"
connectionString="Data Source=|DataDirectory|\sqlCEDB.sdf;Password='somepassword'"
providerName="System.Data.SqlServerCe.3.5" />
</connectionStrings>

Categories