简体   繁体   中英

Winform with EF CodeFirst and Mysql

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 在此输入图像描述 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.. 在此输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM