環境:EntityFramework5.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的webconfig稍加不同。重點還是webconfig配置
mysql中文亂碼問題,請在連線串最後加:Character Set=utf8;