EntityFramework+MySql資料庫(code first方式)
阿新 • • 發佈:2018-11-02
(學習大佬tkbSimplest的CodeFirst開發系列)
一、安裝MySQL 8.0.13
- 系統WIN7 SP1
- 在MySQL官網下載mysql-installer-community-8.0.13.0.msi
MySQL for Visual Studio 1.2.8版本安裝失敗回滾,只安裝1.0.2版本
二、Visual Studio
- 已有VS2010
- MySQL.Data依賴Google.Protobuf,Google.Protobuf依賴.Net 4.5以上,VS2010 不支援.Net 4.5,重新安裝VS2015
- 從NuGet安裝兩個包:MySql.Data和MySql.Data.Entity
- 新建Donator、Context類:
public class Donator { public int DonatorId { get; set; } public string Name { get; set; } public decimal Amount { get; set; } public DateTime DonateDate { get; set; } } [DbConfigurationType(typeof(MySql.Data.EntityFramework.MySqlEFConfiguration))] public class Context : DbContext { public Context() : base("name=CodeFirst") ///呼叫了父類的建構函式,並且傳入了一個鍵值對,鍵是name,值是CodeFirst,這個鍵值對是定義在應用程式的配置檔案中的 { } public DbSet<Donator> Donators { get; set; } }
- 測試:
class Program { static void Main(string[] args) { using (var context = new Context()) { context.Database.CreateIfNotExists();//如果資料庫不存在時則建立 context.Donators.Add( new Donator { DonatorId = 1, Name = "Niu", Amount = 50, DonateDate = DateTime.Now }); context.SaveChanges(); } Console.Write("DB has Created!");//提示DB建立成功 Console.Read(); }
- App.config新增:
<connectionStrings>
<add name="CodeFirst" connectionString="Data Source=localhost;port=3306;Initial Catalog=CodeFirst;user id=root;password=root;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
執行:
'MySql.Data.Entity.EFMySqlCommand.set_DbConnection(System.Data.Common.DbConnection)' to access method 'MySql.Data.MySqlClient.MySqlConnection.get_Settings()' failed."
呃。。。百度半天各種修改,卒。Google一下
Oracle renamed the package to MySql.Data.EntityFramework for v8.x. You need to uninstall MySql.Data.Entity and install MySql.Data.EntityFramework.
- NuGet解除安裝MySql.Data.Entity,安裝MySql.Data.EntityFramework
- 執行:
附:
Navicat連線Mysql 8.0.13報錯:Client does not support authentication protocol requested by server;
開啟MySQL 8.0 Command Line Client,命令:
1. use mysql;
2. alter user 'root'@'localhost' identified with mysql_native_password by '自個的密碼';
3. flush privileges;