前序:
参考:http://www.cnblogs.com/wolf-sun/p/4804617.html
mysql-for-visualstudio-1.2.4.msi 下载该文件,然后运行安装(如果没安装,请先安装)。
Connector/Net 下载该文件,并安装(如果没安装,请先安装)
使用Nuget安装EF
使用Nuget安装mysql提供程序。
创建实体类
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace test1.Models
{
public class User
{
public int Id { get;set;}
[Required]
public String Name{get;set;}
[Required]
public String PassWord { get; set; }
[Required]
public int rolt { get; set; }
}
}
创建上下文
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace test1.Models
{
public class UserContext : DbContext
{
public UserContext() : base("name=UserContext")
{
}
public System.Data.Entity.DbSet<test1.Models.User> Users { get; set; }
}
}
修改web.config
<connectionStrings>
<add name="UserContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=mvcweb;user id=root;password=root;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<!--
<contexts>
<context type="test1.Models.UserContext,test1">
<databaseInitializer type="test1.Models.InitUser,test1"></databaseInitializer>
</context>
</contexts>
-->
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</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.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>