標籤:c# mysql
MySQL安裝好了,今天跟大家交流一下怎麼利用EntityFramework的CodeFirst在MySQL資料庫中建立資料庫
目標框架:.NET Framework 4
第一步:建立一個項目,然後添加如下的引用,這些引用可以在NuGet中添加,也可以到官網中下載然後添加
第二步:在設定檔中添加資料庫節點配置
<span style="font-family:Arial;font-size:10px;"><?xml version="1.0"?><configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> <connectionStrings> <add name="conncodefirst" connectionString="server=192.168.24.184;port=3306;uid=root;pwd=123456;database=code" providerName="MySql.Data.MySqlClient"/> </connectionStrings></configuration></span>
第三步:我們編寫實體類
<span style="font-family:Arial;font-size:10px;">using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;namespace codeFIrst4{ //顧客類 public class customer { [Key] //顧客id public string id { get; set; } //顧客姓名 public string cusName { get; set; } } }</span>
第四步:編寫資料庫上下文
<span style="font-family:Arial;font-size:10px;">using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;namespace codeFIrst4{ //資料庫上下文 public class HotelDBContext:DbContext { public HotelDBContext() : base("name=conncodefirst") { } public DbSet<customer> Customer { get; set; } }}</span>
第五步:編寫建立資料庫代碼
<span style="font-family:Arial;font-size:10px;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace codeFIrst4{ class Program { static void Main(string[] args) { HotelDBContext dbCOntext = new HotelDBContext(); bool flag=dbCOntext.Database.CreateIfNotExists(); if (flag==true) { Console.WriteLine("MySQL資料庫建立成功!"); } else { Console.WriteLine("MySQL資料庫建立失敗!"); } } }}</span>
通過上面簡單的交流,我想大家都應該明白怎麼用CodeFirst來建立一個MySQL資料庫了,一開始學習EF的時候,我們都是在SQL Server資料庫中建立映射,那麼MySQL資料庫和SQL Server資料庫的區別在哪裡呢?第一點:引用不同,MySQL需要引用MySql.Data;第二點:設定檔中的資料庫節點配置不同。除了以上的兩點,其他地方都差不多。
C# 之 EF CodeFirst建立MySQL資料庫