Home  >  Article  >  Database  >  EntityFramework 多数据库链接,MySql,SqlServer,Oracel等

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

WBOY
WBOYOriginal
2016-06-07 15:40:111537browse

环境: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>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>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> />
  
  <connectionstrings>
   <span> //无论多少类型,多少个同类型数据库,尽管加吧</span><em><strong><span>
    <add name="DefaultDB" connectionstring="Server=localhost;Uid=sa;Pwd=ovenjackchain;DataBase=CN9295;" providername="System.Data.SqlClient"></add>
    <add name="DbConMySql" providername="MySql.Data.MySqlClient" connectionstring="Data Source=172.16.205.61;Port=3306;Initial Catalog=WMC;uid=assp;pwd=assp123;"></add></span></strong></em>
  </connectionstrings>
  <appsettings>
    <add key="<span">"<span>webpages:Version</span><span>"</span> value=<span>"</span><span>2.0.0.0</span><span>"</span> />
    <add key="<span">"<span>webpages:Enabled</span><span>"</span> value=<span>"</span><span>false</span><span>"</span> />
    <add key="<span">"<span>PreserveLoginUrl</span><span>"</span> value=<span>"</span><span>true</span><span>"</span> />
    <add key="<span">"<span>ClientValidationEnabled</span><span>"</span> value=<span>"</span><span>true</span><span>"</span> />
    <add key="<span">"<span>UnobtrusiveJavaScriptEnabled</span><span>"</span> value=<span>"</span><span>true</span><span>"</span> />
  </add></add></add></add></add></appsettings>
  <system.web>
    <httpruntime targetframework="<span">"<span>4.5</span><span>"</span> />
    <compilation debug="<span">"<span>true</span><span>"</span> targetFramework=<span>"</span><span>4.5</span><span>"</span> />
    <authentication mode="<span">"<span>Forms</span><span>"</span>>
      <forms loginurl="<span">"<span>~/Account/Login</span><span>"</span> timeout=<span>"</span><span>2880</span><span>"</span> />
    </forms></authentication>
    <pages>
      <namespaces>
        <add>namespace=<span>"</span><span>System.Web.Helpers</span><span>"</span> />
        <add>namespace=<span>"</span><span>System.Web.Mvc</span><span>"</span> />
        <add>namespace=<span>"</span><span>System.Web.Mvc.Ajax</span><span>"</span> />
        <add>namespace=<span>"</span><span>System.Web.Mvc.Html</span><span>"</span> />
        <add>namespace=<span>"</span><span>System.Web.Optimization</span><span>"</span> />
        <add>namespace=<span>"</span><span>System.Web.Routing</span><span>"</span> />
        <add>namespace=<span>"</span><span>System.Web.WebPages</span><span>"</span> />
      </add></add></add></add></add></add></add></namespaces>
    </pages>
    <profile defaultprovider="<span">"<span>DefaultProfileProvider</span><span>"</span>>
      <providers>
        <add name="<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> />
      </add></providers>
    </profile>
    <membership defaultprovider="<span">"<span>DefaultMembershipProvider</span><span>"</span>>
      <providers>
        <add name="<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> />
      </add></providers>
    </membership>
    <rolemanager defaultprovider="<span">"<span>DefaultRoleProvider</span><span>"</span>>
      <providers>
        <add name="<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> />
      </add></providers>
    </rolemanager>
    <sessionstate mode="<span">"<span>InProc</span><span>"</span> customProvider=<span>"</span><span>DefaultSessionProvider</span><span>"</span>>
      <providers>
        <add name="<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> />
      </add></providers>
    </sessionstate>
  </compilation></httpruntime></system.web>
  <system.webserver>
    <validation validateintegratedmodeconfiguration="<span">"<span>false</span><span>"</span> />
    <handlers>
      <remove name="<span">"<span>ExtensionlessUrlHandler-ISAPI-4.0_32bit</span><span>"</span> />
      <remove name="<span">"<span>ExtensionlessUrlHandler-ISAPI-4.0_64bit</span><span>"</span> />
      <remove name="<span">"<span>ExtensionlessUrlHandler-Integrated-4.0</span><span>"</span> />
      <add name="<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>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>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> />
    </add></add></add></remove></remove></remove></handlers>
  </validation></system.webserver>
  <runtime>
    <assemblybinding xmlns="<span">"<span>urn:schemas-microsoft-com:asm.v1</span><span>"</span>>
      <dependentassembly>
        <assemblyidentity name="<span">"<span>System.Web.Helpers</span><span>"</span> publicKeyToken=<span>"</span><span>31bf3856ad364e35</span><span>"</span> />
        <bindingredirect oldversion="<span">"<span>1.0.0.0-2.0.0.0</span><span>"</span> newVersion=<span>"</span><span>2.0.0.0</span><span>"</span> />
      </bindingredirect></assemblyidentity></dependentassembly>
      <dependentassembly>
        <assemblyidentity name="<span">"<span>System.Web.Mvc</span><span>"</span> publicKeyToken=<span>"</span><span>31bf3856ad364e35</span><span>"</span> />
        <bindingredirect oldversion="<span">"<span>1.0.0.0-4.0.0.0</span><span>"</span> newVersion=<span>"</span><span>4.0.0.0</span><span>"</span> />
      </bindingredirect></assemblyidentity></dependentassembly>
      <dependentassembly>
        <assemblyidentity name="<span">"<span>System.Web.WebPages</span><span>"</span> publicKeyToken=<span>"</span><span>31bf3856ad364e35</span><span>"</span> />
        <bindingredirect oldversion="<span">"<span>1.0.0.0-2.0.0.0</span><span>"</span> newVersion=<span>"</span><span>2.0.0.0</span><span>"</span> />
      </bindingredirect></assemblyidentity></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"></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.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></add>
    </dbproviderfactories></strong></span></em></span>
  </system.data>


<p>以上配置部分,斜体和红字的是我修改过的,其他都是项目自动产生的。</p>
<p> </p>
<p>测试:</p>
<p>
</p>
<pre class="brush:php;toolbar:false"><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></summary></span>
        <span>///</span><span> 类目
        </span><span>///</span> <span></span>
        <span>public</span> <span>string</span> Category { <span>get</span>; <span>set</span><span>; }

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

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

        </span><span>///</span> <span><summary></summary></span>
        <span>///</span><span> 父节点
        </span><span>///</span> <span></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>());
</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></do_category></pluralizingtablenameconvention></mycontext></user></pluralizingtablenameconvention></mycontext>

 

 

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

 

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Oracle Berkeley DB和SqlServer如何选Next article:SqlServer 自动化分区方案

Related articles

See more