[C#][EF] 使用Code First方式連接MySql資料庫

  • 8450
  • 0
  • C#
  • 2013-03-14

摘要:[C#][EF] 使用Code First方式連接MySql資料庫

1. 首先開啟一個新的專案,在此以WPF為例。

2. 透過Nuget 管理工具安裝 Entitty Framework, 安裝完成後會在方案目錄下建立一個packages的目錄,並且在專案目錄下增加一個App.Config檔案。

3. 加入EntityFramework.dll (位置在 packages\Entity Framework Version\lib\.Net Framework Version\下)

4. 修改 App.Config, 預設的內容為:


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

將configSections 及 entityFramework兩個區段的內容註解掉 並加上connectionStrings區段, 並在區段中加入連線字串的設定, 例如:

    <add name="MySql" connectionString="Server=localhost; Database=testdb; Persist Security Info=True; UId=userID; Pwd=password; " providerName="MySql.Data.MySqlClient"/>

修改後的 App.Config 如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!--<configSections>
    --><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --><!--
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>-->
  <!--<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>-->
  <connectionStrings>
    <add name="MySql" connectionString="Server=localhost; Database=testdb; Persist Security Info=True; UId=userID; Pwd=password; " providerName="MySql.Data.MySqlClient"/>
  </connectionStrings>
</configuration>

 

5. 建立一個Patient類別 


using System.IO;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WpfApplication1
{
    public class Patient
    {
        /// 
        /// 系統使用; System ID
        /// 
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid PatientID { get; private set; }

        /// 
        /// 病歷編號; Patient Number
        /// 
        [Required]
        [MaxLength(20)]
        public string PatientNo { get; set; }

        /// 
        /// 病患姓名; Patient's Name
        /// 
        [Required]
        [MaxLength(50)]
        public string PatientName { get; set; }

        /// 
        /// 個人識別證碼; Personal Identity Number
        /// 
        [Required]
        [MaxLength(20)]
        public string PIN { get; set; }


        /// 
        /// 出生年月日; Birthday;
        /// 
        [Required]
        public DateTime Birthday { get; set; }

        /// 
        /// 初診日期; First Visit Day
        /// 
        [Required]
        public DateTime FirstVisitDay { get; set; }

        public Patient()
        {
            FirstVisitDay = DateTime.Today;
        }
    }
}

 

6. 建立一個繼承DbContext的類別 , 並增加帶有 string 參數的建構子。類別中有一個屬性 Patients ,  資料型別為 DbSet<Patient> 。 


using System.Data.Entitys;

namespace WpfApplication1
{
    public class TestContext:DbContext
    {
        public TestContext(string connectionString)
            : base(connectionString)
        {

        }

        public DbSet Patients { get; set; }
    }
}

 

7. 接下來只要在程式中透過 new TestContext("Name=MySql").Database.CreateIfNotExists(); 或是在第一次執行SaveChange(); 時,系統便會替我們產生相關的DB Schema了。

8. 如果在建立DB Schema 時產生如下圖的Exception 時,代表所使用的 MySql .NetConnector 是舊版的。只要更新到 6.6.5 版本以上就可以了。