首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >实体框架5.0代码优先-在.Net 4.5上使用MySQL连接器6.6.5.0

实体框架5.0代码优先-在.Net 4.5上使用MySQL连接器6.6.5.0
EN

Stack Overflow用户
提问于 2013-05-07 11:38:43
回答 4查看 18.8K关注 0票数 7

就我而言,我无法让我的C# WinApp使用MySql数据库,使用MySql连接器6.6.5.0 (MySql.Data参考资料)和MySql Entity 6.5.4.0 (MySql.Data.Entity参考资料)来处理Entity Framework5.0。在Visual Studio2012上使用.Net框架4.5。在撰写本文时,上面的版本都是最新的稳定版本。

这是我在app.config上的资料

代码语言:javascript
运行
复制
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.data>
    <DbProviderFactories>
      <add name="MySQL Data Provider" 
           invariant="MySql.Data.MySqlClient" 
           description=".Net Framework Data Provider for MySQL" 
           type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="MyConnectionName" 
         connectionString="Server=mysql13.myserver.com.br;Database=mydb;User Id=username;Pwd=pa$$w0rd;" 
         providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data">
    </defaultConnectionFactory>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.6.5.0" newVersion="6.6.5.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

在代码中

用户类

代码语言:javascript
运行
复制
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Permission> Permissions { get; set; }

    public User()
    {
        Permissions = new List<Permission>();
    }
}

public class Permission
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class UserContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Permission> Permissions { get; set; }
}

创建新记录

代码语言:javascript
运行
复制
        using (var db = new UserContext())
        {
            Permission permission1 = new Permission() { Name = "Permission 1", Description = "The desc 1" };
            Permission permission2 = new Permission() { Name = "2nd Perm", Description = "Desc2" };
            User user = new User() { Name = "Joao" };
            user.Permissions.Add(permission1);
            user.Permissions.Add(permission2);

            db.Users.Add(user);
            db.SaveChanges();
        }

我在db.Users.Add(user);行得到了一个异常

代码语言:javascript
运行
复制
System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=Failed to set Database.DefaultConnectionFactory to an instance of the 'MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data' type as specified in the application configuration. See inner exception for details.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Internal.AppConfig.<.ctor>b__1()
       at System.Lazy`1.CreateValue()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Lazy`1.get_Value()
       at System.Data.Entity.Internal.AppConfig.get_DefaultConnectionFactory()
       [removing the rest of the stack]
  InnerException: System.InvalidCastException
       HResult=-2147467262
       Message=Unable to cast object of type 'MySql.Data.MySqlClient.MySqlClientFactory' to type 'System.Data.Entity.Infrastructure.IDbConnectionFactory'.
       Source=EntityFramework
       StackTrace:
            at System.Data.Entity.Internal.AppConfig.<.ctor>b__1()
       InnerException: 

我已经尝试了几种方法,包括在DbProviderFactories部分添加Culture=neutral, PublicKeyToken=c5687fc88969c44d,但都没有用。

我使用NuGet包管理器添加了实体框架、MySql数据连接器和MySql.Data.Entity。

我见过许多其他有类似问题的帖子,但找不到明确的解决方案,特别是版本组合EF 5+ MySql连接器6.6.5.0。

有没有人做到这一点?你能同时发布app.config和代码以使其工作吗?

EN

回答 4

Stack Overflow用户

发布于 2013-05-07 14:59:13

正如前面提到的here,MySQL连接器6.6.5只支持实体框架4.3。到目前为止,我个人使用过它,效果很好。但是,如果您特别需要Entity Framework5,您将需要使用现在支持here的MySQL连接器6.6.7Beta。不过,我还没有尝试过v6.6.7。

更新1:您可以找到在MySQL连接器6.6 here中使用EF4.3代码优先的博客文章。

更新2:使用EF 4.3和.NET连接器6.6.5 here的示例MySql 4.5控制台应用程序。

票数 5
EN

Stack Overflow用户

发布于 2013-05-08 13:11:40

听起来好像有一些奇怪的程序集解析问题。尝试删除配置文件中的assemblyBinding元素,然后运行NuGet的Add-BindingRedirect命令。

票数 0
EN

Stack Overflow用户

发布于 2013-05-08 15:03:29

我的大部分产品web.config。我拿出了所有公司特有的东西..。此外,此配置是为使用IIS压缩的MVC4/EF5/OData 5.2设置的。不需要非常复杂的stuff...most。但我想你想要我的原始配置作为参考。

代码语言:javascript
运行
复制
<?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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="EdgeService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <appSettings>
    <add key="log4net.Config.Watch" value="True" />
    <add key="log4net.Config" value="EdgeService.log4net.config" />
    <add key="PullVersionPeriod" value="30000" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <httpRuntime maxRequestLength="12288" maxUrlLength="10999" maxQueryStringLength="2097151"/>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <add assembly="System.Web.Helpers" />
      </assemblies>
    </compilation>
    <authentication mode="Windows" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
  </system.web>
  <system.data>
    <DbProviderFactories>
      <clear />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description="ADO.Net driver for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
  </system.serviceModel>
  <system.webServer>
    <handlers>
      <remove name="svc-Integrated-4.0" />
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
    </modules>
    <security>
      <requestFiltering>
        <requestLimits maxQueryString="100000" />
      </requestFiltering>
      <authentication>
        <!--C:\Windows\System32\inetsrv\config\applicationHost.config-->
        <anonymousAuthentication enabled="false" />
        <windowsAuthentication enabled="true">
          <providers>
            <clear />
            <add value="Negotiate" />
          </providers>
        </windowsAuthentication>
      </authentication>
    </security>
    <httpCompression>
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" dynamicCompressionLevel="4" />
      <dynamicTypes>
        <add enabled="true" mimeType="Application/*" />
        <add enabled="true" mimeType="application/atom+xml;type=feed;charset=utf-8" />
      </dynamicTypes>
    </httpCompression>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data" publicKeyToken="C5687FC88969C44D" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.6.4.0" newVersion="6.6.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data.Entity" publicKeyToken="c5687fc88969c44d" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.6.4.0" newVersion="6.6.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="MySql.Web" publicKeyToken="c5687fc88969c44d" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.6.4.0" newVersion="6.6.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.4.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16410817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档