EntityFramework 다중 데이터베이스 링크, MySql, SqlServer, Oracel 등

31228 단어 sqlserver
환경: EntityFramework 5.0,MySql5.6,MSSQL2012
EF는 강력한 ORM 도구로 진정한 의미의 다중 데이터베이스 링크는 서로 다른 유형의 데이터베이스와 같은 유형의 데이터베이스 여러 개의 라이브러리를 가리킨다. EF는 이 점을 잘 지원한다. 다음은 간단하게 설명한다.
MVC4. 만들기0,Framework4.5에 대한 기본 항목 및 WebConfig 구성에 초점을 맞춥니다.
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<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>
  <connectionStrings>
    //      ,         ,     <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;" />
  </connectionStrings>
  <appSettings>
    <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 targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <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>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
<!--<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>--> <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.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data> </configuration>

상기 설정 부분에서 사체와 빨간 글자는 내가 수정한 것이고 다른 것은 모두 항목이 자동으로 생성한 것이다.
 
테스트:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MySql.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.ComponentModel.DataAnnotations;

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }

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

    public class DO_Category
    {
        public DO_Category() { }

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

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

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

        /// <summary>
        ///    
        /// </summary>
        public Guid FatherId { get; set; }

        public string CreateUser { get; set; }

        public DateTime CreateTime { get; set; }

        public string ModifyUser { get; set; }

        public DateTime? ModifyTime { get; set; }


        [Timestamp]
        public Byte[] RowVersion { get; set; }

    }


    public class User
    {
        public Guid Id { get; set; }
        public string UserName { get; set; }
    } 

    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            //Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
//  MySql   
            var context = new MyContext("DbConMySql");
            context.user.Add(new User { Id = Guid.NewGuid(), UserName = "jackchain" });
            context.SaveChanges();
           var userlist= context.user.ToList();
//  SQLServer     
           var sqlc = new SQLContext("DefaultDB");
           ViewBag.clist = sqlc.category.ToList();
           return View(userlist);
        }
    }
}

 
 
OK. 마음껏 음미해.EF6의 웹config는 조금 다릅니다.중점은 웹config 설정입니다
 
mysql 중국어 부호화 문제, 연결열에 마지막으로:Character Set=utf8;

좋은 웹페이지 즐겨찾기