简体   繁体   English

使用EF CodeFirst和Mysql进行Winform

[英]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? 您好我正在尝试使用实体框架'CodeFirst'将Winql Db(空)与WinForm连接但我有第一个问题1.Can EntityFramework'CodeFirst'在Mysql数据库中创建表和列? and If EF can do that as I suppose then why displays this exception when I try to add a record in a table. 如果EF可以像我想的那样做,那么当我尝试在表中添加记录时,为什么会显示此异常。 Here's the Code 这是守则

Using: 使用:

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

App.config 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 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); 在此行db.LoginModel.Add(user); Program.cs 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. 不要将实际的连接字符串传递到上下文中,只需将web.config中连接字符串元素的name属性传递给上下文的基本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. 编辑:我没有使用MySql所以如果这是错误请纠正我。 You don't have a provider specified in your EntityFramework section of your web.config. 您没有在web.config的EntityFramework部分中指定提供程序。 I did a quick search and found this web.config for mysql: 我做了一个快速搜索,发现这个mysql的web.config:

<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 我在这里找到了web.config

Add the provider to your web.config and let me know what you get. 将提供程序添加到web.config并告诉我你得到了什么。

I found something interesting here 我发现这里有些有趣

You can pass a full connection string to DbContext instead of just the database or connection string name. 您可以将完整的连接字符串传递给DbContext,而不仅仅是数据库或连接字符串名称。 By default this connection string is used with the System.Data.SqlClient provider; 默认情况下,此连接字符串与System.Data.SqlClient提供程序一起使用; this can be changed by setting a different implementation of IConnectionFactory onto context.Database.DefaultConnectionFactory. 这可以通过将IConnectionFactory的不同实现设置到context.Database.DefaultConnectionFactory来更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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