准备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
在web项目中model文件夹下创建Users实体和MyUserContext上下文对象
Users实体类
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Web;namespacePMS.Web.Models
{///
///users实体对象///
public classUsers
{public int Id { get; set; }public string UserName { get; set; }//默认string映射到mysql里是longtext类型的,加长度之后就变成varchar了
[MaxLength(30)]public string PassWord { get; set; }
}
}
MyUserContext上下文对象
usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Web;namespacePMS.Web.Models
{
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]public classMyUserContext : DbContext
{publicMyUserContext()
:base("name=MyContext")//web.config中connectionstring的名字
{
}public DbSet Users { get; set; }
}
}
HomeController.cs
usingPMS.Web.Models;usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;namespacePMS.Web.Controllers
{public classHomeController : Controller
{publicActionResult Index()
{
InitData();returnView();
}private voidInitData()
{
Database.SetInitializer(new DropCreateDatabaseAlways());var context = newMyUserContext();//插入一行值
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属性
namespacePMS.Web.Migrations
{usingSystem;usingSystem.Data.Entity;usingSystem.Data.Entity.Migrations;usingSystem.Linq;internal sealed class Configuration : DbMigrationsConfiguration{publicConfiguration()
{
AutomaticMigrationsEnabled= true;
}protected override voidSeed(PMS.Web.Models.MyUserContext context)
{//This method will be called after migrating to the latest version.//You can use the DbSet.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
重新运行项目。此时已经可以正常运行