C# 之 EF CodeFirst建立MySQL資料庫

來源:互聯網
上載者:User

標籤: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資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.