'Option not supported' error when using SQL Server with MySQL - c#

I'm trying to retrieve data from both MySQL and SQL Server on the same console application. I manage to retrieve data from MySQL, however when I trying to retrieve data from SQL Server, I got System.ArgumentException: 'Option not supported. Parameter name: multipleactiveresultsets' error.
The following is my app.config:
<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="MySQLDb" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=sakila;uid=some_user;password=some_password"/>
<add name="SQLDb" providerName="System.Data.SqlClient" connectionString="data source=USER-PC\SQLEXPRESS;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"/>
</connectionStrings>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
</configuration>
And my C#:
#region MySQL.
{
var dbContext = new MySQLDb();
var dbSet = dbContext.Set<Actor>();
var actors = dbSet.ToList();
}
#endregion
#region SQLServer.
{
var dbContext = new SQLDb();
var dbSet = dbContext.Set<User>();
var users = dbSet.ToList(); // <-- Throw exception.
}
#endregion
If I disable entityFramework section in app.config and MySQL code block in my C# code, I can retrieve data from SQL Server without any issue.
Version info
MySQL.Data.Entity 6.10.8
NET Framework 4.6.1
Any idea?
Update 1
Found out that the connection type for MySQLDb is MySql.Data.MySqlClient.MySqlConnection, so that works just fine. But when instantiating SQLDb, the connection type is still MySql.Data.MySqlClient.MySqlConnection instead of System.Data.SqlClient.SqlConnection. How should we fix this?

The issue is that we are using MySql.Data.Entity.MySqlEFConfiguration (in the app.config) which set the default connection factory to use MySqlConnectionFactory.
The solution is to use a custom DbConfiguration in place of MySql.Data.Entity.MySqlEFConfiguration to deter from setting the default connection factory.
public class MySQLDbConfiguration : DbConfiguration
{
public MySQLDbConfiguration()
{
SetProviderServices(MySqlProviderInvariantName.ProviderName, new MySqlProviderServices());
SetProviderFactory(MySqlProviderInvariantName.ProviderName, new MySqlClientFactory());
}
}
Declare the instance as readonly somewhere in the code,
private static readonly MySQLDbConfiguration DBConfig = new MySQLDbConfiguration();
and set the configuration PRIOR TO using any EF features
DbConfiguration.SetConfiguration(DBConfig);
And our app.config now becomes
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="MySQLDb" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=sakila;uid=some_user;password=some_password"/>
<add name="SQLDb" providerName="System.Data.SqlClient" connectionString="data source=USER-PC\SQLEXPRESS;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"/>
</connectionStrings>
</configuration>
If you're opt to use app.config instead of deriving a custom DbConfiguration, you can do the following
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- Alternative to custom DbConfiguration. -->
<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>
<providers>
<provider invariantName = "MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
</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.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</DbProviderFactories>
</system.data>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="MySQLDb" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=sakila;uid=some_user;password=some_password"/>
<add name="SQLDb" providerName="System.Data.SqlClient" connectionString="data source=USER-PC\SQLEXPRESS;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"/>
</connectionStrings>
</configuration>

If you are using asp net 5.0, install the Nuget found here, but first uninstall Mysql.data.

Related

WebConfig & EF 6 & DbFirst & Oracle - Unable cast OracleConnection to SqlConnection

I'm using EF 6 with a database-first approach and Oracle. However, on connecting, the following exception is thrown:
Unable to cast object of type 'Oracle.ManagedDataAccess.Client.OracleConnection' to type 'System.Data.SqlClient.SqlConnection'
I'm a little confused ...
My web.config looks actually right:
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.18.3, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<connectionStrings>
<add name="TestConnection"
providerName="System.Data.EntityClient"
connectionString="metadata=res://*/Model.Entities.PimEntities.csdl|res://*/Model.Entities.PimEntities.ssdl|res://*/Model.Entities.PimEntities.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="data source=TestDataSource;persist security info=True;user id=XXX;password=XXX"" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.DataAccess.Client" />
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver"
invariant="Oracle.ManagedDataAccess.Client"
description="Oracle Data Provider for .NET, Managed Driver"
type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.18.3, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<entityFramework>
<defaultConnectionFactory type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Oracle.ManagedDataAccess.Client"
type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.122.18.3, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</entityFramework>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="TestDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=TestServer.TestDomain.loc)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=TestService))) " />
</dataSources>
<settings>
<setting name="BindByName" value="true" />
</settings>
</version>
</oracle.manageddataaccess.client>
</configuration>
To be sure I checked my DbContext class:
public partial class TestEntities : DbContext
{
public DbSetProvider() : base("name=TestConnection")
{
}
}
Seems legit.
After hours of researching I just created a new web application, imported specific nuget packages and set up ef with code first approach without generating the .edmx file.
This works as intended.
The used web.config for the code first approach is the same like before, except:
<add name="TestConnection"
providerName="Oracle.ManagedDataAccess.Client"
connectionString="User Id=XXX;Password=XXX;Data Source=TestDataSource" />
Now I'm completely done.
Nothing changed except the providerName and of course the metadata information.
So my question is: why is Entity Framework trying to convert OracleConnection to SqlConnection?
Or how to fix my issue and using the database-first approach?
Excuse me for my imperfect English skills.
Thanks in advance.
According to the docs here, your connection string providerName should be the Oracle one:
providerName="Oracle.ManagedDataAccess.Client"
not the providerName="System.Data.EntityClient"

Migrate database generated by entity framework to sqlserver

I made a application with database generated by entity framework(code first) and now I want to make my application working on other computer. I instaled sqlserver there and made all the tables in the database (I am working just with localhost database). Now I wanted to connect my database with application, I thought that all what I need to do is just change connection string. But I am not able to connect to my database.
Here is how looks my app.config file:
<?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.5.2" />
</startup>
<connectionStrings>
<add name="InzerceConnection" connectionString="Data source=VRBASPC\SQLEXPRESS;Initial Catalog=AdvertisingSystemDB;Trusted_Connection=true;MultipleActiveResultSets=true" />
<!--This is how my connection string works by default <add name="InzerceConnection" connectionString="Server=(localdb)\\MSSQLLocalDb;Database=Inzerce_Dev;Trusted_Connection=true;MultipleActiveResultSets=true" />-->
<!--<add name="InzerceConnection" connectionString="Server=localhost\SQLEXPRESS;Database=AdvertisingSystemDB;Trusted_Connection=true;MultipleActiveResultSets=true" />-->
</connectionStrings>
<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>
</configuration>
I tried a lot of combination of connection string, but none worked.
I am not sure how to setup my config file to connect to database.
Thank you for any advice.
Sory for my english its not my native language.
In your context override the OnConfiguring method.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connstr = ConfigurationManager.ConnectionStrings["InzerceConnection"].ToString();
optionsBuilder.UseSqlServer(connstr);
}
Check in your database context.
Database context and name attributes should be the same.
For Example
public class DatabaseContext : DbContext
{
public DbSet<Content> Contents { get; set; }
public DbSet<Category> Categories { get; set; }
public DatabaseContext()
{
Database.SetInitializer(new MyInitializer());
}
}
ConnectionStrings in your app.config
<connectionStrings>
<add name="DatabaseContext" providerName="System.Data.SqlClient" connectionString="Data source=VRBASPC\SQLEXPRESS;Initial Catalog=AdvertisingSystemDB;Trusted_Connection=true;MultipleActiveResultSets=true" />
</connectionStrings>

Entity Framework not saving changes to a Local DB

I'm new to C# and Entity Framework and I'm trying to write an application to improve my knowledge.
I think I've set up everything correctly and I don't get any type of error. The problem is that I can not add a new record to localDb in Visual Studio 2017.
Any ideas? Thanks in advance.
Here is my code
private void Save_btn_Click(object sender, EventArgs e)
{
var context = new Database1Entities();
var aMemberdef = new Members()
{
FirstName = Name_txt.Text,
LastName = LastName_txt.Text
};
context.Members.Add(aMemberdef);
context.SaveChanges();
}
and here my app.config:
<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="Database1Entities"
connectionString="metadata=res://*/EF.Model1.csdl|res://*/EF.Model1.ssdl|res://*/EF.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB; attachdbfilename=|DataDirectory|\Data\Database1.mdf; initial catalog=Database1; 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>
I think there is some mistake in the app config file but the connection string was generated by entity framework. So I'm stuck MyDB Structure
Because your localdb is copied to bin folder every time you run it. It gets overwritten everytime you run/debug it. Main file in the project folder is not updated.
For detailed answer:
https://social.msdn.microsoft.com/Forums/en-US/393bddc6-0b85-4c27-9475-27172e50d2d9/entity-framework-doesnt-save-new-record-into-database?forum=adodotnetentityframework

Postgresql and Entity Framework

In my project I am trying to use Entity Framework along with PostgreSql. But I am not able to connect to my database. I am not getting any error, it just gets stuck. I think something is wrong with my app.config, but I am not able to find out what.
App.config:
<?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="Npgsql.NpgsqlFactory, Npgsql" />
<providers>
<provider invariantName="Npgsql"
type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider" invariant="Npgsql"
description="Data Provider for PostgreSQL"
type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="Entities"
connectionString="server=localhost;user id=postgres;password=4321;database=postgis"
providerName="Npgsql" />
</connectionStrings>
</configuration>
DbContext:
public class Entities : DbContext
{
public Entities() : base("Entities")
{
}
//rest of the code
}
mycode.cs
using (var db = new Entities()) // when debug it stuck here and keep running
{
// some test code
}
EDIT:
I get the following error :
"The Entity Framework provider type 'Npgsql.NpgsqlServices, Npgsql.EntityFramework' registered in the application config file for the ADO.NET provider with invariant name 'Npgsql' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application.
The problem points to a wrong provider type or assembly name.
<entityFramework>
<defaultConnectionFactory type="Npgsql.NpgsqlFactory, Npgsql" />
<providers>
<provider invariantName="Npgsql"
type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
</providers>
</entityFramework>
The assembly name is wrong. The assembly installed by the EntityFramework6.Npgsql package is EntityFramework6.Npgsql.dll. In fact, adding the package to a new project sets the correct provider line:
<providers>
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>

App.config doesn't save some changes after app relaunch

I have a next App.config file:
<configuration>
<configSections>
<sectionGroup name="UserSettingsGroup">
<section name="dbConnectionString" type="System.Configuration.ConnectionStringsSection" />
<section name="reportsFolderSettings" type="System.Configuration.DictionarySectionHandler" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<UserSettingsGroup>
<dbConnectionString>
<add name="Host" providerName="System.Data.sqlclient" connectionString="localhost" />
<add name="Port" providerName="System.Data.sqlclient" connectionString="3050" />
........
........ etc.
</dbConnectionString>
<reportsFolderSettings>
<add key="ReportsFolder" value="C:\" />
</reportsFolderSettings>
</UserSettingsGroup>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.data>
<DbProviderFactories>
<remove invariant="FirebirdSql.Data.FirebirdClient" />
<add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient" />
</DbProviderFactories>
</system.data>
And then I made some changes in runtime in my app's settings (I've changed the connections strings and the path for saving app's reports) and for applying them I used this code:
private void SaveSettings() {
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
ConnectionStringsSection connectionSettings = (ConnectionStringsSection)config.SectionGroups.Get("UserSettingsGroup").Sections.Get("dbConnectionString");
connectionSettings.ConnectionStrings["Host"].ConnectionString = txtServer.Text;
connectionSettings.ConnectionStrings["Port"].ConnectionString = txtPort.Text;
connectionSettings.ConnectionStrings["DbPath"].ConnectionString = txtDBPath.Text;
connectionSettings.ConnectionStrings["User"].ConnectionString = txtUser.Text;
connectionSettings.ConnectionStrings["Password"].ConnectionString = txtPassword.Text;
connectionSettings.ConnectionStrings["Charset"].ConnectionString = cboCharset.Text;
Hashtable sectionReportsFolder = ConfigurationManager.GetSection(config.SectionGroups.Get("UserSettingsGroup").Sections.
Get("reportsFolderSettings").SectionInformation.SectionName) as Hashtable;
sectionReportsFolder.Clear();
sectionReportsFolder.Add("ReportsFolder", tbo_reportfolder.Text);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("dbConnectionString");
ConfigurationManager.RefreshSection("reportsFolder");
}
At first glance, everything works well - I see the changes while my app is working but for some reason the app doesn't save the "reportsFolderSettings" and after relaunch I see only default value "C:\".
P.S I launch the app from .exe from "\bin\release" folder, NOT from Visual studio.
OK, I recreated Your problem and I had the same problem ; )
The problem is DictionarySectionHandler supports only reading values
This is not direct answer to Your question but it works
To work I do this:
I change type of section from:
<section name="reportsFolderSettings" type="System.Configuration.DictionarySectionHandler" />
to use the AppSettingsSection
<section name="reportsFolderSettings" type="System.Configuration.AppSettingsSection" />
Then I change:
var sectionReportsFolder = config.SectionGroups["UserSettingsGroup"].Sections["reportsFolderSettings"] as AppSettingsSection;
sectionReportsFolder.Settings.Clear();
sectionReportsFolder.Settings.Add("ReportsFolder", tbo_reportfolder.Text);
And then everything is work good. I tested this.

Categories

Resources