首页 > 数据库 > mysql教程 > EntityFramework 多数据库链接,MySql,SqlServer,Oracel等

EntityFramework 多数据库链接,MySql,SqlServer,Oracel等

WBOY
发布: 2016-06-07 15:40:11
原创
1575 人浏览过

环境:EntityFramework5.0,MySql5.6,MSSQL2012 EF是强大的ORM工具,真正意义上的多数据库链接指的是不同类型的数据库,以及同种类型的数据库多个库,EF很好的支持这一点,下面简单演示下: 创建一个MVC4.0,Framework4.5的基本项目,然后重点是WebConfig配

环境:EntityFramework5.0,MySql5.6,MSSQL2012

EF是强大的ORM工具,真正意义上的多数据库链接指的是不同类型的数据库,以及同种类型的数据库多个库,EF很好的支持这一点,下面简单演示下:

创建一个MVC4.0,Framework4.5的基本项目,然后重点是WebConfig配置:

<?xml version=<span>"</span><span>1.0</span><span>"</span> encoding=<span>"</span><span>utf-8</span><span>"</span>?>
<!--<span>
  For more information on how to configure your ASP.NET application, please visit
  http:</span><span>//</span><span>go.microsoft.com/fwlink/?LinkId=152368</span>
  -->
<configuration>
  <configdivs>
    <!-- For more information on Entity Framework configuration, visit http:<span>//</span><span>go.microsoft.com/fwlink/?LinkID=237468 -->
    <div name=<span>"</span><span>entityFramework</span><span>"</span> type=<span>"</span><span>System.Data.Entity.Internal.ConfigFile.EntityFrameworkdiv, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</span><span>"</span> requirePermission=<span>"</span><span>false</span><span>"</span> />
  </configdivs>
  <connectionStrings>
   <span> //无论多少类型,多少个同类型数据库,尽管加吧</span><em><strong><span>
    <add name="DefaultDB" connectionString="Server=localhost;Uid=sa;Pwd=ovenjackchain;DataBase=CN9295;" providerName="System.Data.SqlClient"/>
    <add name="DbConMySql" providerName="MySql.Data.MySqlClient"  connectionString="Data Source=172.16.205.61;Port=3306;Initial Catalog=WMC;uid=assp;pwd=assp123;" /></span></strong></em>
  </connectionStrings>
  <appSettings>
    <add key=<span>"</span><span>webpages:Version</span><span>"</span> value=<span>"</span><span>2.0.0.0</span><span>"</span> />
    <add key=<span>"</span><span>webpages:Enabled</span><span>"</span> value=<span>"</span><span>false</span><span>"</span> />
    <add key=<span>"</span><span>PreserveLoginUrl</span><span>"</span> value=<span>"</span><span>true</span><span>"</span> />
    <add key=<span>"</span><span>ClientValidationEnabled</span><span>"</span> value=<span>"</span><span>true</span><span>"</span> />
    <add key=<span>"</span><span>UnobtrusiveJavaScriptEnabled</span><span>"</span> value=<span>"</span><span>true</span><span>"</span> />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework=<span>"</span><span>4.5</span><span>"</span> />
    <compilation debug=<span>"</span><span>true</span><span>"</span> targetFramework=<span>"</span><span>4.5</span><span>"</span> />
    <authentication mode=<span>"</span><span>Forms</span><span>"</span>>
      <forms loginUrl=<span>"</span><span>~/Account/Login</span><span>"</span> timeout=<span>"</span><span>2880</span><span>"</span> />
    </authentication>
    <pages>
      <namespaces>
        <add <span>namespace</span>=<span>"</span><span>System.Web.Helpers</span><span>"</span> />
        <add <span>namespace</span>=<span>"</span><span>System.Web.Mvc</span><span>"</span> />
        <add <span>namespace</span>=<span>"</span><span>System.Web.Mvc.Ajax</span><span>"</span> />
        <add <span>namespace</span>=<span>"</span><span>System.Web.Mvc.Html</span><span>"</span> />
        <add <span>namespace</span>=<span>"</span><span>System.Web.Optimization</span><span>"</span> />
        <add <span>namespace</span>=<span>"</span><span>System.Web.Routing</span><span>"</span> />
        <add <span>namespace</span>=<span>"</span><span>System.Web.WebPages</span><span>"</span> />
      </namespaces>
    </pages>
    <profile defaultProvider=<span>"</span><span>DefaultProfileProvider</span><span>"</span>>
      <providers>
        <add name=<span>"</span><span>DefaultProfileProvider</span><span>"</span> type=<span>"</span><span>System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</span><span>"</span> connectionStringName=<span>"</span><span>DefaultConnection</span><span>"</span> applicationName=<span>"</span><span>/</span><span>"</span> />
      </providers>
    </profile>
    <membership defaultProvider=<span>"</span><span>DefaultMembershipProvider</span><span>"</span>>
      <providers>
        <add name=<span>"</span><span>DefaultMembershipProvider</span><span>"</span> type=<span>"</span><span>System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</span><span>"</span> connectionStringName=<span>"</span><span>DefaultConnection</span><span>"</span> enablePasswordRetrieval=<span>"</span><span>false</span><span>"</span> enablePasswordReset=<span>"</span><span>true</span><span>"</span> requiresQuestionAndAnswer=<span>"</span><span>false</span><span>"</span> requiresUniqueEmail=<span>"</span><span>false</span><span>"</span> maxInvalidPasswordAttempts=<span>"</span><span>5</span><span>"</span> minRequiredPasswordLength=<span>"</span><span>6</span><span>"</span> minRequiredNonalphanumericCharacters=<span>"</span><span>0</span><span>"</span> passwordAttemptWindow=<span>"</span><span>10</span><span>"</span> applicationName=<span>"</span><span>/</span><span>"</span> />
      </providers>
    </membership>
    <roleManager defaultProvider=<span>"</span><span>DefaultRoleProvider</span><span>"</span>>
      <providers>
        <add name=<span>"</span><span>DefaultRoleProvider</span><span>"</span> type=<span>"</span><span>System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</span><span>"</span> connectionStringName=<span>"</span><span>DefaultConnection</span><span>"</span> applicationName=<span>"</span><span>/</span><span>"</span> />
      </providers>
    </roleManager>
    <sessionState mode=<span>"</span><span>InProc</span><span>"</span> customProvider=<span>"</span><span>DefaultSessionProvider</span><span>"</span>>
      <providers>
        <add name=<span>"</span><span>DefaultSessionProvider</span><span>"</span> type=<span>"</span><span>System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</span><span>"</span> connectionStringName=<span>"</span><span>DefaultConnection</span><span>"</span> />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration=<span>"</span><span>false</span><span>"</span> />
    <handlers>
      <remove name=<span>"</span><span>ExtensionlessUrlHandler-ISAPI-4.0_32bit</span><span>"</span> />
      <remove name=<span>"</span><span>ExtensionlessUrlHandler-ISAPI-4.0_64bit</span><span>"</span> />
      <remove name=<span>"</span><span>ExtensionlessUrlHandler-Integrated-4.0</span><span>"</span> />
      <add name=<span>"</span><span>ExtensionlessUrlHandler-ISAPI-4.0_32bit</span><span>"</span> path=<span>"</span><span>*.</span><span>"</span> verb=<span>"</span><span>GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS</span><span>"</span> modules=<span>"</span><span>IsapiModule</span><span>"</span> scriptProcessor=<span>"</span><span>%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll</span><span>"</span> preCondition=<span>"</span><span>classicMode,runtimeVersionv4.0,bitness32</span><span>"</span> responseBufferLimit=<span>"</span><span>0</span><span>"</span> />
      <add name=<span>"</span><span>ExtensionlessUrlHandler-ISAPI-4.0_64bit</span><span>"</span> path=<span>"</span><span>*.</span><span>"</span> verb=<span>"</span><span>GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS</span><span>"</span> modules=<span>"</span><span>IsapiModule</span><span>"</span> scriptProcessor=<span>"</span><span>%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll</span><span>"</span> preCondition=<span>"</span><span>classicMode,runtimeVersionv4.0,bitness64</span><span>"</span> responseBufferLimit=<span>"</span><span>0</span><span>"</span> />
      <add name=<span>"</span><span>ExtensionlessUrlHandler-Integrated-4.0</span><span>"</span> path=<span>"</span><span>*.</span><span>"</span> verb=<span>"</span><span>GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS</span><span>"</span> type=<span>"</span><span>System.Web.Handlers.TransferRequestHandler</span><span>"</span> preCondition=<span>"</span><span>integratedMode,runtimeVersionv4.0</span><span>"</span> />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns=<span>"</span><span>urn:schemas-microsoft-com:asm.v1</span><span>"</span>>
      <dependentAssembly>
        <assemblyIdentity name=<span>"</span><span>System.Web.Helpers</span><span>"</span> publicKeyToken=<span>"</span><span>31bf3856ad364e35</span><span>"</span> />
        <bindingRedirect oldVersion=<span>"</span><span>1.0.0.0-2.0.0.0</span><span>"</span> newVersion=<span>"</span><span>2.0.0.0</span><span>"</span> />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name=<span>"</span><span>System.Web.Mvc</span><span>"</span> publicKeyToken=<span>"</span><span>31bf3856ad364e35</span><span>"</span> />
        <bindingRedirect oldVersion=<span>"</span><span>1.0.0.0-4.0.0.0</span><span>"</span> newVersion=<span>"</span><span>4.0.0.0</span><span>"</span> />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name=<span>"</span><span>System.Web.WebPages</span><span>"</span> publicKeyToken=<span>"</span><span>31bf3856ad364e35</span><span>"</span> />
        <bindingRedirect oldVersion=<span>"</span><span>1.0.0.0-2.0.0.0</span><span>"</span> newVersion=<span>"</span><span>2.0.0.0</span><span>"</span> />
      </dependentAssembly>
    </assemblyBinding>
  </runtime><br><span>下面这里注释掉,否则会默认根据默认工厂来找</span>
 <span> <em><strong><span><!--<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    --><!--<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF5">
    </defaultConnectionFactory>--><!--
  </entityFramework>--></span></strong></em></span>
  <system.data><br><span>如果你还有其他的数据库类型,那么只需要在这里加配置即可</span>
    <span><em><span><strong><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.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories></strong></span></em></span>
  </system.data>
</configuration>
登录后复制

以上配置部分,斜体和红字的是我修改过的,其他都是项目自动产生的。

 

测试:

<span>using</span><span> System;
</span><span>using</span><span> System.Collections.Generic;
</span><span>using</span><span> System.Configuration;
</span><span>using</span><span> System.Data.Entity;
</span><span>using</span><span> System.Linq;
</span><span>using</span><span> System.Web;
</span><span>using</span><span> System.Web.Mvc;
</span><span>using</span><span> MySql.Data.Entity;
</span><span>using</span><span> System.Data.Entity.ModelConfiguration.Conventions;
</span><span>using</span><span> System.ComponentModel.DataAnnotations;

</span><span>namespace</span><span> MvcEFMySql.Controllers
{
    </span><span>//</span><span>这里是mysql的</span>
    <span>public</span> <span>class</span><span> MyContext : DbContext
    {
       
        </span><span>public</span> MyContext(<span>string</span><span> DefaultDb)
            : </span><span>base</span><span>(DefaultDb)
        {
            </span><span>//</span><span>Database.DefaultConnectionFactory =  MySql.Data.MySqlClient.MySqlClientFactory;
            </span><span>//</span><span>Database.Connection.ConnectionString = ;</span>
            Database.SetInitializer<MyContext>(<span>null</span><span>);
        }

        </span><span>protected</span> <span>override</span> <span>void</span><span> OnModelCreating(DbModelBuilder modelBuilder)
        {
            </span><span>//</span><span>已经存在的数据库,不然会出现负数</span>
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention><span>();
            </span><span>base</span><span>.OnModelCreating(modelBuilder);
        }

        </span><span>public</span> DbSet<User> user { <span>get</span>; <span>set</span><span>; }
    }
    </span><span>//</span><span>这里是sqlserver的</span>
    <span>public</span> <span>class</span><span> SQLContext : DbContext
    {
        </span><span>public</span> SQLContext(<span>string</span><span> DefaultDb)
            : </span><span>base</span><span>(DefaultDb)
        {
            </span><span>//</span><span>Database.DefaultConnectionFactory =  MySql.Data.MySqlClient.MySqlClientFactory;
            </span><span>//</span><span>Database.Connection.ConnectionString = ;</span>
            Database.SetInitializer<MyContext>(<span>null</span><span>);
        }

        </span><span>protected</span> <span>override</span> <span>void</span><span> OnModelCreating(DbModelBuilder modelBuilder)
        {
            </span><span>//</span><span>已经存在的数据库,不然会出现负数</span>
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention><span>();
            </span><span>base</span><span>.OnModelCreating(modelBuilder);
        }

        </span><span>public</span> DbSet<DO_Category> category { <span>get</span>; <span>set</span><span>; }
    }

    </span><span>public</span> <span>class</span><span> DO_Category
    {
        </span><span>public</span><span> DO_Category() { }

        [Key]
        </span><span>public</span> Guid Id { <span>get</span>; <span>set</span><span>; }
        </span><span>///</span> <span><summary></span>
        <span>///</span><span> 类目
        </span><span>///</span> <span></summary></span>
        <span>public</span> <span>string</span> Category { <span>get</span>; <span>set</span><span>; }

        </span><span>///</span> <span><summary></span>
        <span>///</span><span> 图标
        </span><span>///</span> <span></summary></span>
        <span>public</span> <span>string</span> IconName { <span>get</span>; <span>set</span><span>; }

        </span><span>///</span> <span><summary></span>
        <span>///</span><span> 排序
        </span><span>///</span> <span></summary></span>
        <span>public</span> <span>int</span> OrderIndex { <span>get</span>; <span>set</span><span>; }

        </span><span>///</span> <span><summary></span>
        <span>///</span><span> 父节点
        </span><span>///</span> <span></summary></span>
        <span>public</span> Guid FatherId { <span>get</span>; <span>set</span><span>; }

        </span><span>public</span> <span>string</span> CreateUser { <span>get</span>; <span>set</span><span>; }

        </span><span>public</span> DateTime CreateTime { <span>get</span>; <span>set</span><span>; }

        </span><span>public</span> <span>string</span> ModifyUser { <span>get</span>; <span>set</span><span>; }

        </span><span>public</span> DateTime? ModifyTime { <span>get</span>; <span>set</span><span>; }


        1438906181
        </span><span>public</span> Byte[] RowVersion { <span>get</span>; <span>set</span><span>; }

    }


    </span><span>public</span> <span>class</span><span> User
    {
        </span><span>public</span> Guid Id { <span>get</span>; <span>set</span><span>; }
        </span><span>public</span> <span>string</span> UserName { <span>get</span>; <span>set</span><span>; }
    } 

    </span><span>public</span> <span>class</span><span> HomeController : Controller
    {
        </span><span>//</span>
        <span>//</span><span> GET: /Home/</span>

        <span>public</span><span> ActionResult Index()
        {
            </span><span>//</span><span>Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
</span><span>//</span><span>操作MySql数据库</span>
            <span>var</span> context = <span>new</span> MyContext(<span>"</span><span>DbConMySql</span><span>"</span><span>);
            context.user.Add(</span><span>new</span> User { Id = Guid.NewGuid(), UserName = <span>"</span><span>jackchain</span><span>"</span><span> });
            context.SaveChanges();
           </span><span>var</span> userlist=<span> context.user.ToList();
</span><span>//</span><span>获取SQLServer数据库内容</span>
           <span>var</span> sqlc = <span>new</span> SQLContext(<span>"</span><span>DefaultDB</span><span>"</span><span>);
           ViewBag.clist </span>=<span> sqlc.category.ToList();
           </span><span>return</span><span> View(userlist);
        }
    }
}</span>
登录后复制

 

 

ok尽情品味吧。EF6的webconfig稍加不同。重点还是webconfig配置

 

mysql中文乱码问题,请在连接串最后加:Character Set=utf8;

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板