二,引用dll:web
一、采用Nuget安装EF6.0.2;sql
二、采用Nuget安装MySql.Data.Entity.EF6数据库
注意:要采用Nuget进行安装,不然可能会缺乏相应的dll或者是配置信息app
2、配置 web.config或app.configide
一、将entitframework节点替代为:ui
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">spa
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>code
<providers>server
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />get
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
二、添加 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这个表 } }}