Enity Framework With MySQL - config file could not be loaded - mysql

I am trying to change SQL Database type from MSSQL to MySQL inside .NET web app.
I followed this:
https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
and updating Web.config files.
<configuration>
<configSections>
<section name="AdWordsApi" type="System.Configuration.DictionarySectionHandler" />
<!-- 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>
...
</configuration>
...
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.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="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.27.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</entityFramework>
<connectionStrings>
<add name="DefaultConnection" providerName="MySql.Data.MySqlClient" connectionString="Server=XYZ;Database=XYZ;Uid=XYZ;Password=XYZ;" />
</connectionStrings>
When trying to Enable-Migrations I am getting:
Checking if the context targets an existing database...
System.InvalidOperationException: The DbConfiguration type 'MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.EntityFramework' specified in the application config file 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=260883 for more information. ---> System.TypeLoadException: Nie można załadować typu 'MySql.Data.Entity.MySqlEFConfiguration' z zestawu 'MySql.Data.EntityFramework'.
w System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
w System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
w System.Type.GetType(String typeName, Boolean throwOnError)
w System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationLoader.TryLoadFromConfig(AppConfig config)
--- Koniec śladu stosu wyjątków wewnętrznych ---
w System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationLoader.TryLoadFromConfig(AppConfig config)
w System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
w System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInitialCreateInternal(DbConnectionInfo connectionInfo, String contextTypeName, String contextAssemblyName, String migrationsNamespace, Boolean auto, String migrationsDir)
w System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInitialCreate.<>c__DisplayClass0_0.<.ctor>b__0()
w System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.b__0()
w System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
The DbConfiguration type 'MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.EntityFramework' specified in the application config file 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=260883 for more information.```
I din't update any class, only configuration files so far. My context class looks like this:
namespace Repository.Models
{
public class AppContext : IdentityDbContext, IAppContext
{
public AppContext()
: base("DefaultConnection")
{
}
public static AppContext Create()
{
return new AppContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
...
}
}
I tried modifying above class into with no luck:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class AppContext : DbContext, IAppContext
{
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
...
public AppContext()
: base()
{
}
// Constructor to use on a DbConnection that is already opened
public AppContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Entity<Car>().MapToStoredProcedures();
}
}

1- You Need to Install The NuGet Package MySql.Data.Entity
2- Update the Configuration Type of DbContextFile:
[DbConfigurationType(typeof(MySqlEfConfiguration))]
public class AppDbContext : DbContext{.....}
3- Change the Connection String provider name to: "MySql.Data.MySqlClient"
providerName="MySql.Data.MySqlClient"
4- Test With Migrations
As I See, the problem is that you need to modify the DbContext Class

Related

Unrecognized attribute 'name' when using <remove /> in a ConfigurationElementCollection

I have a custom ConfigurationSection that contains a custom ConfigurationElementCollection with custom ConfigurationElement instances. The <add> and <clear> tags work fine in the configuration file, but using <remove> generates the following exception during my unit test:
System.Configuration.ConfigurationErrorsException: Unrecognized attribute 'name'. Note that attribute names are case-sensitive.
The configuration file is pretty simple. Here's the inner-part of the test section in question:
<exceptionHandling>
<policies>
<clear />
<add name="default" shouldLog="true" shouldShow="true"/>
<add name="initialization" shouldLog="true" shouldShow="true"/>
<add name="security" shouldLog="true" shouldShow="true"/>
<add name="logOnly" shouldLog="true" shouldShow="false"/>
<add name="unhandled" shouldLog="true" shouldShow="true"/>
<add name="test" shouldLog="false" shouldShow="false"/>
<remove name="test"/>
</policies>
</exceptionHandling>
The following is the relevant code for the configuration classes (some has been elided for brevity).
public sealed class ExceptionHandlingSection : ConfigurationSection
{
[ConfigurationProperty("policies", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(PolicyElementCollection), AddItemName = "add", RemoveItemName = "remove", ClearItemsName = "clear")]
public PolicyElementCollection Policies => (PolicyElementCollection)base["policies"];
}
public sealed class PolicyElementCollection : ConfigurationElementCollection
{
// pretty boiler plate
}
public sealed class PolicyElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get => (string)this["name"];
set => this["name"] = value;
}
// other properties
}
What needs to be done to get <remove> to work as shown in the test configuration file?
The answer to this turns out to be really simple.
I read a few things talking about XML attributes, but fundamentally it's looking for a key property. This can be assigned by a property of the ConfigurationPropertyAttribute. To get the <remove> tag to work all I need to do is change my ConfigurationElement class as follows:
public sealed class PolicyElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get => (string)this["name"];
set => this["name"] = value;
}
// other properties
}

troubles with vb net, mysql and entity framework 6 sbyte type

I've defined a project in visual studio 2015, I've used ADO NET Code first to connect with a mysql database (mysql connector 6.9.9), and now, having the model, I'm trying to use entity framework 6.
I've installed from nuget 'mysql entity framework 6.9.9' in my project, but when I try to connect with the model, next message is shown:
SBYTE THERE IS NO STORE TYPE Corresponding to the conceptual side type
'SBYTE' of primitive type 'SBYTE'
.Net framework 4.5.2
Any suggest??
Thanks!!
SByte is not a data type supported by the providers (at least is not supported by SQL Server, SQL Server CE, Microsoft Access, MySQL).
If you Really Want a class with an SByte, the best way is to use a [private] backing and expose the SByte property.
This is the model for a private backing field.
public class Info
{
public int Id { get; set; }
[MaxLength(50)]
public string Description { get; set; }
public sbyte SByte
{
get
{
return (sbyte) SByteBackingField;
}
set
{
SByteBackingField = value;
}
}
private int SByteBackingField { get; set; }
public class InfoMap : EntityTypeConfiguration<Info>
{
public InfoMap()
{
ToTable("Infoes69");
Property(_ => _.SByteBackingField).HasColumnName("SByte");
Ignore(_ => _.SByte);
}
}
}
and in context you need to add the configuration
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Info.InfoMap());
}
The issue is that you can't use SByte property in queries.
I experienced this when using MySQL because EntityFramework defaults to using SQL Server - which does not have this data type.
The solution (for me) had 2 parts, either of which caused the same error:
Go into Web.Config, and set the correct provider for entity framework
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
Make sure that the connection string was set properly.
YMMV!

MySQL and Entity Framework issues

I am attempting to use EF6 to connect to a MySql DB. I've looked at NUMEROUS examples and they all look different. I see so many different ways and they are not like connecting to Oracle, which I have experience with.
public string GetWebinarList()
{
string str = "";
string connectionString = "server=127.0.0.1;port=3306;UserId=user;database=db;password=pwd;CharSet=utf8;Persist Security Info=True;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (webinarListDbContext context = new webinarListDbContext())
{
var list = context.WebinarLists.ToString();
str = list;
}
connection.Close();
}
return str;
}
The above actually looks more like connecting through ADO.DB than EF6.
The Context definition:
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class webinarListDbContext : DbContext
{
public webinarListDbContext() : this("MonkeyFist") { }
public webinarListDbContext(string connStringName) : base(connStringName) { }
static webinarListDbContext()
{
// static constructors are guaranteed to only fire once per application.
// I do this here instead of App_Start so I can avoid including EF
// in my MVC project (I use UnitOfWork/Repository pattern instead)
DbConfiguration.SetConfiguration(new MySql.Data.Entity.MySqlEFConfiguration());
}
public DbSet<WebinarList> WebinarLists { get; set; }
}
Web.Config:
<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.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
<connectionStrings>
<add name="MonkeyFist" providerName="MySql.Data.MySqlClient" connectionString="server=127.0.0.1;port=3306;UserId=user;database=db;password=pwd;CharSet=utf8;Persist Security Info=True;"/>
</connectionStrings>
</system.data>
<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="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</entityFramework>
But this is what I see when I inspect the context object:
What the heck is it using a SQLClient connection for vs. a MySQLClient? And Why would MonkeyFist be set as the Database? How would I connect EF6 to MySQL?
The reason you are seeing this behaviour is that you are not actually passing your connection object to your context. Instead you are passing the string "MonkeyFist", which the context assumes is the name of a db. Since it cannot find this db in your config file, it creates a local db with the same name.
See here: https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.113).aspx
If the parameterless DbContext constructor is called from a derived context, then the name of the derived context is used to find a connection string in the app.config or web.config file. If no connection string is found, then the name is passed to the DefaultConnectionFactory registered on the Database class. The connection factory then uses the context name as the database name in a default connection string. (This default connection string points to .\SQLEXPRESS on the local machine unless a different DefaultConnectionFactory is registered.) Instead of using the derived context name, the connection/database name can also be specified explicitly by passing the name to one of the DbContext constructors that takes a string.
Pass your connection object to your context.

Windows Service: EF + MySql without app.config

At the moment I'm writing a windows service.
I'm already using EntityFramework with MSSQL database which is working perfectly. Now I have to use MySql parallely. But I can't manage to get it running ... I would like to avoid using the app.config and configure EntityFramework via the constructor of my class derived from DbContext.
I have a SqlContext class:
public class SqlContext : DbContext
{
public IDbSet<ServiceauftragSource> ServiceauftragSource { get; set; }
public SqlContext(string connectionString)
: base(connectionString)
{
}
public SqlContext(DbConnection connection)
: base(connection, true)
{
this.Configuration.LazyLoadingEnabled = true;
}
}
In the constructor of my UnitOfWork I try to create my SqlContext:
public SqlUnitOfWork()
{
const string connStr = "server=127.0.0.1;uid=myuser;pwd=mypw;database=mydb;";
MySqlConnection conn = new MySqlConnection(connectionString);
this.Context = new SqlContext(conn);
}
This didn't work. I get the following message when trying to access the database:
Unable to determine the DbProviderFactory type for connection of type 'MySql.Data.MySqlClient.MySqlConnection'. Make sure that the ADO.NET provider is installed or registered in the application config.
Neither did:
public SqlUnitOfWork()
{
this.SetConnectionString();
this.Context = new SqlContext(connectionString);
}
private void SetConnectionString()
{
this.connectionString = "Data Source=" + debugDatabaseServer + ";Initial Catalog=" + debugDatabaseName
+ ";User ID=" + debugDatabaseUsername + ";Password=" + debugDatabasePassword
+ ";Trusted_Connection=False;Persist Security Info=True;";
}
I'm not sure why but I think this is because I haven't told my context its provider (according to other threads on SO it has to be MySql.Data.MySqlClient). But where and how to?
References of the project:
Update
I tried to use my 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>
<connectionStrings>
<add name="MySqlContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;
port=3306;database=***;uid=***;password=***"/>
</connectionStrings>
<entityFramework>
<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>
When accessing the database I get the following error:
Object reference not set to an instance of an object.
I think this is because my service can't access the app.config after it's being installed. I ensured that app.config is MyService.exe.config after build ...
I've been using MySQL with EF for quite some time pretty flawlessly, what yo need to do is add the following line above your DBContext
[DbConfigurationType(typeof (MySql.Data.Entity.MySqlEFConfiguration))]
so in your case the snippet would look like
[DbConfigurationType(typeof (MySql.Data.Entity.MySqlEFConfiguration))]
public class SqlContext : DbContext
{
public IDbSet<ServiceauftragSource> ServiceauftragSource { get; set; }
public SqlContext(string connectionString)
: base(connectionString)
{
}
public SqlContext(DbConnection connection)
: base(connection, true)
{
this.Configuration.LazyLoadingEnabled = true;
}
}
as for your connection string, i tend to store mine in the web config and then string format for whatever db,server or user i need to create a context for - hope that helps!
NB Im presuming you have your refs to MySQL.data and EF6 as well!

Entity framework 5.0 code-first with MySQL in WPF

This walkthrough works great with SQL Express:
http://msdn.microsoft.com/en-us/library/gg197522(v=VS.103).aspx
I would like it to work with MySQL. I've done some research but none of the techniques I've found has been able to do it for me. Ideally I would like to do something like this:
<entityFramework>
<defaultConnectionFactory type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
</entityFramework>
This doesn't work (I have MySQL Connector Net 6.5.4 installed & MySql.Data referenced). I've tried deriving from IDbConnection factory as shown in this class here:
http://www.vworker.com/RentACoder/misc/BidRequests/ShowBidRequest.asp?lngBidRequestId=1563829
and then using:
<entityFramework>
<defaultConnectionFactory type="SchoolModel.MySqlConnectionFactory, SchoolModel" />
but that doesn't work either. Can anybody please give me some pointers as to how to get this to work?
Many thanks.
To use Connector 6.5.4 with code-first EF5 on VS2012 you need:
Install MySql Connector 6.5.4 msi
Open VS2012 x86 Command Prompt as Admin and execute:
gacutil /i "C:\Program Files (x86)\MySQL\Connector NET 6.5.4\Assemblies\v4.0\mysql.data.dll"
gacutil /i "C:\Program Files (x86)\MySQL\Connector NET 6.5.4\Assemblies\v4.0\mysql.data.entity.dll"
Add in your project's App.config this code to <configuration> section:
<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.5.4.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
/>
</DbProviderFactories>
</system.data>
Now add references to MySql.Data and MySql.Data.Entity to your solution and some code like this (I create MySqlConnection, then pass it to constructor of MyDbContext)
public class MyDbContext : DbContext
{
public MyDbContext(DbConnection connection) : base(connection, true) { } ​
public DbSet<Product> Products { get; set; }
}
[Table("sund_jshopping_products")]
public class Product
{
[Key]
[Column("product_id")]
public int Id { get; set; }
[Column("product_ean")]
public string Ean { get; set; }
[Column("product_manufacturer_id")]
public int OperatorId { get; set; }
[Column("months_status")]
public string MonthsStatus { get; set; }
[Column("extra_field_5")]
public string SideId { get; set; }
}
Connector 6.5.4 does not support code-first with EF 5. Actually it does not support code first.
You can try using dot net connector (at least the trial version).
Did you set the Datasource to MySQL while setting up your db connection. Also, click and make sure "Test Connection" succeeds before trying a connection directly from the code.