使用EF Code First和Mysql进行Winform

时间:2014-01-10 20:47:42

标签: c# mysql .net winforms entity-framework

您好我正在尝试使用Entity Framework'CodeFirst'将Winql Db(空)与WinForm连接但我有第一个问题1.Can EntityFramework'CodeFirst'在Mysql数据库中创建表和列?如果EF可以像我想的那样做,那么当我尝试在表中添加记录时,为什么会显示此异常。这是代码

使用:

  • 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)
                { }
            }


    }

并且以下是此行db.LoginModel.Add(user);处显示 enter image description here的例外情况 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();

        }
    }
}

和参考文献.. enter image description here

1 个答案:

答案 0 :(得分:2)

不要将实际的连接字符串传递到上下文中,只需将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")
    { }
}

然后你可以正常使用:

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

编辑:我还没有使用MySql,所以如果这是错误请纠正我。您没有在web.config的EntityFramework部分中指定提供程序。我做了一个快速搜索,发现这个mys.的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中,让我知道你得到了什么。

I found something interesting here

  

您可以将完整的连接字符串传递给DbContext,而不仅仅是数据库或连接字符串名称。默认情况下,此连接字符串与System.Data.SqlClient提供程序一起使用;这可以通过将IConnectionFactory的不同实现设置到context.Database.DefaultConnectionFactory来更改。