实现连接到MYSQL数据库。
我的数据库版本是是5.7的。
先安装 MySQL-Connector-Net
下载地址:http://dev.mysql.com/downloads/connector/net/
我下载安装的是mysql-connector-net-6.10.9.msi
接下来,在MVC项目中,右键项目名,管理NuGet程序包,浏览,搜索下载Mysql.Data和Mysql.Data.EntityFramework。
Mysql.Data我记得之前安装的是6.10.9的,然后先安装了一次Mysql.Data.EntityFramework,没有安装最新的版本,读取数据库时代码报错了:未能加载文件或程序集“EntityFramework, Version=6.0.0.0, Culture=neutral等一堆,我将Mysql.Data.EntityFramework升级到最新版本后,Mysql.Data也被自动更新到最新版本了。
接下来,在Models中添加好自己需要的类
public class UserModels
{
[Key]
public int id { get; set; }
[Display(Name = "用户名")]
public string UserName { get; set; }
[Display(Name = "密码")]
public string PassWord { get; set; }
[Display(Name = "权限")]
public int Level { get; set; }
[Display(Name = "备注")]
public string Remark { get; set; }
[Display(Name = "电话")]
public string Telephone { get; set; }
[Display(Name = "邮箱")]
public string Email { get; set; }
}
public class BookModels
{
[Key]
public int id { get; set; }
[Display(Name = "书名")]
public string BookName { get; set; }
[Display(Name = "作者")]
public string Author { get; set; }
[Display(Name = "类型")]
public string Type { get; set; }
[Display(Name = "租金(天)")]
public decimal RentalPrice { get; set; }
[Display(Name = "售卖金额")]
public decimal BuyPrice { get; set; }
[Display(Name = "状态")]
public string State { get; set; }
}
自己的数据库中记得添加好相应的数据。记得模型类的名字和表名一定要相同
在Web.config中添加配置,记得把相应的服务器地址,用户名,密码,数据库等信息配置正确。
<connectionStrings>
<add name="DefaultConnection" connectionString="server=127.0.0.1;user id=root;password=123456;persist security info=True;database=mvc_db;charset=utf8;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
然后添加类MyContext(我添加在了App_Start文件夹中)
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyContext : DbContext
{
public DbSet<UserModels> Users { get; set; }
public DbSet<BookModels> Books { get; set; }
public MyContext(): base("DefaultConnection")
{
Database.CreateIfNotExists();
}
}
看看测试效果。
OK了,可以准备接下来的工作了!