二,引用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這個表 } }}