0

Hello I'm trying to connect a Mysql Db (empty) with a WinForm using Entity Framework 'CodeFirst' but I have this first question 1.Can EntityFramework 'CodeFirst' create tables and columns into a Mysql Database? and If EF can do that as I suppose then why displays this exception when I try to add a record in a table. Here's the Code

Using:

  • EF v6
  • MySqlConnector v6.7.4.0
  • .NET 4.0 Framework
  • VS2012

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>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity">
    </defaultConnectionFactory>
  </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.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="ConnectionStringName" connectionString="server=localhost;Database=auth;uid=root;pwd=1234;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

MySqlContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


    namespace Unify.RoleCreator
    {

            public class MySqlContext : System.Data.Entity.DbContext
            {
                public System.Data.Entity.DbSet<LoginModel> LoginModel { get; set; }
                public System.Data.Entity.DbSet<Roles> Roles { get; set; }

                public MySqlContext(string connString)
                    : base(connString)
                { }
            }


    }

And Here is where the exception displays enter image description here at this line db.LoginModel.Add(user); Program.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unify.RoleCreator;
using System.Configuration;

namespace RoleCreatorv3
{
    static class Program
    {

        [STAThread]
        static void Main()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MySqlContext>());

            var connString =  ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString();

            using (var db = new MySqlContext(connString))
            {
                var user = new LoginModel { User = "admin", Pass= 123 };
                db.LoginModel.Add(user);
                db.SaveChanges();
            }
            Console.WriteLine("All ok!");
            Console.Read();

        }
    }
}

and the References.. enter image description here

1 Answer 1

2

Instead of passing the actual connection string into your context, just pass the name attribute of the connection string element in your web.config to your context's base DbContext.

public class MySqlContext : System.Data.Entity.DbContext
{
    public System.Data.Entity.DbSet<LoginModel> LoginModel { get; set; }
    public System.Data.Entity.DbSet<Roles> Roles { get; set; }

    public MySqlContext()
    : base("ConnectionStringName")
    { }
}

Then you can use normally:

using (var db = new MySqlContext()) {
    ...
}

Edit: I haven't worked with MySql so please correct me if this is wrong. You don't have a provider specified in your EntityFramework section of your web.config. I did a quick search and found this web.config for mysql:

<entityFramework>
  <providers>
    <provider invariantName="MySql.Data.MySqlClient"
      type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity"/> 
  </providers>
</entityFramework>
<system.data>
  <DbProviderFactories>   
    <remove invariant="MySql.Data.MySqlClient"></remove>
    <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.7.2.0"/>
  </DbProviderFactories>
</system.data>

I found that web.config here

Add the provider to your web.config and let me know what you get.

I found something interesting here

You can pass a full connection string to DbContext instead of just the database or connection string name. By default this connection string is used with the System.Data.SqlClient provider; this can be changed by setting a different implementation of IConnectionFactory onto context.Database.DefaultConnectionFactory.

Sign up to request clarification or add additional context in comments.

5 Comments

I just did that and now displays this exception at the same line "No Entity Framework provider found for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file" @Smith.h.Neil
I just edited my answer with what I think you need. Apologies if it doesn't work, I'm not familiar with mysql and setting up entity for mysql.
No Problem,App.config file displays a previous exception in line Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MySqlContext>()); "The 'Instance' member of the Entity Framework provider type 'MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity, Version=6.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'. Entity Framework providers must inherit from this class and the 'Instance' member must return the singleton instance of the provider."@Smith.h.Neil
Looks like that's due to a version issue. Check this link: stackoverflow.com/questions/19698165/mysql-and-asp-net-identity. Apparently, MySQL Connector does not support EF6 so you'll either need to downgrade to EF5 or get MySQL Connector's alpha.
Already downgrade to version 5 and MysqlConnector 6.7.4.0 and did not work @Smith.h.Neil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.