二,引用dll:
1、采用Nuget安装EF6.0.2;
2、采用Nuget安装MySql.Data.Entity.EF6
注意:要采用Nuget进行安装,否则可能会缺少相应的dll或者是配置信息
二、配置 web.config或app.config
1、将entitframework节点替代为:
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="MySql.Data.MySqlClient"
type="MySql.Data.MySqlClient.MySqlProviderServices,
MySql.Data.Entity.EF6" />
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices,
EntityFramework.SqlServer" />
</providers>
</entityFramework>
2、添加 ConnectionString节点:
<connectionStrings>
<add name="MyContext" connectionString="Data
Source=localhost;port=3306;Initial Catalog=数据库名称;user
id=Mysql的登录用户名;password=Mysql server密码;"
providerName="MySql.Data.MySqlClient"/> 连接mySQL 数据库
<add name="TestDB" connectionString="Data Source=.;Initial Catalog=MyTest;User ID=sa;Password=123456;" providerName="System.Data.SqlClient"/> MSSQL 数据库
</connectionStrings>
三 建立模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DBModel
{
[Table("UserInfo")]
public partial class UserInfo
{
[Key]
[Column(TypeName = "uniqueidentifier")]
Guid id { get; set; }
[Column(TypeName = "nvarchar")]
[MaxLength(50)]
string userName{get;set;}
[Column(TypeName = "nvarchar")]
[MaxLength(50)]
[DataType(DataType.Password)]
string password { get; set; }
}
}
四 建立数据上下文
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using DBModel;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Infrastructure;
namespace DB
{
public partial class DBContext :DbContext
{
public DBContext()
: base("name=TestDB")
{
}
DbSet<UserInfo> UserInfo { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//移除复数表名的契约 不允许将表名变为复数形式 默认为UserInfos modelBuilder.Conventions.Remove<IncludeMetadataConvention>();//防止黑幕交易 要不然每次都要访问 EdmMetadata这个表
}
}
}