EF Code First 连接MySql
Posted songjianhui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EF Code First 连接MySql相关的知识,希望对你有一定的参考价值。
看了很多文章,尝试了很多次总是进行不下去,整理一下,以便日后查看。
1、创建ASP.NET MVC项目(EFCodeFirst)
1.1、右键点击引用选择管理NuGet程序包下载MySql.Data.Entity.dll(有依懒项,会自动下载MySql.Data.dl 和 EntityFramework.dll)
1.2、修改Web.config文件(如下图)
2、创建类库(EFCodeFirst.DataAccess)
2.1、右键添加-->新建项-->选择数据-->选择ADO.NET实体数据模型-->空Code First模型(也可以不用这一步,但DatabaseAccess.cs文件需要自己创建)
2.1、右键点击引用选择管理NuGet程序包下载MySql.Data.Entity.dll(有依懒项,会自动下载MySql.Data.dl 如下图)
2.2、修改文件 DatabaseAccess.cs
修改之前:
修改之后:
代码如下:
namespace EFCodeFirst.DataAccess { using IdentityAuth.Common; using IdentityAuth.Model.Sys; using mysql.Data.MySqlClient; using System; using System.Data.Common; using System.Data.Entity; using System.Linq; public class DatabaseAccess : DbContext { #region 构造函数和初始化 private static string connectionStr { get; set; } private static DbConnection GetConnection() { if (String.IsNullOrEmpty(connectionStr)) connectionStr = ConfigHelper.GetConnectionStr("EFCodeFirst"); if (String.IsNullOrEmpty(connectionStr)) throw new Exception("数据库连接字符串为空,请在Config文件里配置"); DbConnection dbConnection = new MySqlConnection() { ConnectionString = connectionStr }; return dbConnection; } public DatabaseAccess() : base(DatabaseAccess.GetConnection(), true) { Database.SetInitializer<DatabaseAccess>(null); } #endregion #region 系统表 /// <summary> /// 系统用户信息 /// </summary> public DbSet<SysUserEntity> UserEntities { get; set; } /// <summary> /// 角色信息 /// </summary> public DbSet<SysRoleEntity> RoleEntities { get; set; } /// <summary> /// 系统菜单信息 /// </summary> public DbSet<SysMenuEntity> MenuEntities { get; set; } /// <summary> /// 角色权限信息 /// </summary> public DbSet<SysRoleAuthEntity> RoleAuthEntities { get; set; } /// <summary> /// 角色用户信息 /// </summary> public DbSet<SysRoleUserEntity> RoleUserEntities { get; set; } #endregion } }
2.3、修改App.config文件(如下图)
App.config文件如下:
<?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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider> </providers> </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.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/> </startup> </configuration>
3、迁移
3.1、打开程序包管理控制器,默认项目选择 EFCodeFirst.DataAccess(也就是CodeFirst迁移目录,如下图)
3.2、添加迁移配置 Enable-Migrations(生成以下文件并会出现错误,如图)
3.3、解决3.2出现的错误,修改生成文件 Configuration.cs(如下图)
代码如下:
namespace EFCodeFirst.DataAccess.Migrations { using System; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.History; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<EFCodeFirst.DataAccess.DatabaseAccess> { public Configuration() { AutomaticMigrationsEnabled = false; SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator()); SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema)); } protected override void Seed(EFCodeFirst.DataAccess.DatabaseAccess context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. } } public class MySqlHistoryContext : HistoryContext { public MySqlHistoryContext(DbConnection connection, string defaultSchema) : base(connection, defaultSchema) {} protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired(); modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired(); } } }
3.4、添加一个合并迁移命令行:Add-Migration [Name](eg:Add-Migration Add_Base_Table) Name 为一个合并的名称,自定义,最好不重复
3.5、生成SQL:Update-Database -Script(如果不需要SQL可不用执行)
3.6、迁移到数据库:Update-Database
以上是关于EF Code First 连接MySql的主要内容,如果未能解决你的问题,请参考以下文章
亲测Asp.net Mvc5 + EF6 code first 方式连接MySQL总结
EF Code First Mysql 到 SQL Server