准备mysql for vs工具
mysql-connector-net-6.8.3.msi 网盘地址:http://pan.baidu.com/s/1jHDWINk
mysql-for-visualstudio-1.1.4.msi 网盘地址:http://pan.baidu.com/s/1eSwemno
打开VS工具-》库程序包管理器-》程序包管理器控制平台
安装EF和mysql依赖包
1.PM> Install-Package MySql.Data.Entity -Version 6.9.8
2.PM> Install-Package EntityFramework
安装完成之后配置数据库连接字符串connectionStrings
<connectionStrings> <add name="MyContext" connectionString="Data Source=localhost;port=3307;Initial Catalog=mybook;user id=root;password=root;" providerName="MySql.Data.MySqlClient" /> </connectionStrings>
在web项目中model文件夹下创建Users实体和MyUserContext上下文对象
Users实体类
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace PMS.Web.Models { /// <summary> /// users实体对象 /// </summary> public class Users { public int Id { get; set; } public string UserName { get; set; } //默认string映射到mysql里是longtext类型的,加长度之后就变成varchar了 [MaxLength(30)] public string PassWord { get; set; } } }
MyUserContext上下文对象
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace PMS.Web.Models { [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] public class MyUserContext : DbContext { public MyUserContext() : base("name=MyContext")//web.config中connectionstring的名字 { } public DbSet<Users> Users { get; set; } } }
HomeController.cs
using PMS.Web.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; namespace PMS.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { InitData(); return View(); } private void InitData() { Database.SetInitializer(new DropCreateDatabaseAlways<MyUserContext>()); var context = new MyUserContext(); //插入一行值 context.Users.Add(new Users { UserName = "EF6-MySQL-Code-First" }); context.SaveChanges(); } } }
运行项目,如果出现“无法检查模型兼容性,因为数据库不包含模型元数据。只能检查使用 Code First 或 Code First 迁移创建的数据库的模型兼容性。”
在Visual Studio中对其进行迁移
1.PM> Enable-Migrations
2.配置Configuration的AutomaticMigrationsEnabled属性
namespace PMS.Web.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<PMS.Web.Models.MyUserContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(PMS.Web.Models.MyUserContext 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. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
3.PM> Update-Database -Force
重新运行项目。此时已经可以正常运行
时间: 2024-10-17 10:07:45