文件首頁
MySQL Connector/NET 開發人員指南
相關文件 下載本手冊
PDF (US Ltr) - 1.3Mb
PDF (A4) - 1.3Mb


MySQL Connector/NET 開發人員指南  /  ...  /  在 EF Core 中使用 Code First 建立資料庫

7.2.1 在 EF Core 中使用 Code First 建立資料庫

Code First 方法可讓您在程式碼中定義實體模型、從模型建立資料庫,然後將資料新增至資料庫。MySQL Connector/NET 與多個版本的 Entity Framework Core 相容。如需特定相容性資訊,請參閱表 7.2「Connector/NET 版本和 Entity Framework Core 支援」

以下範例顯示從現有程式碼建立資料庫的流程。雖然此範例使用 C# 語言,但您可以使用任何 .NET 語言,並在 Windows、macOS 或 Linux 上執行產生的應用程式。

  1. 為此範例建立主控台應用程式。

    1. 使用 .NET Core 命令列介面 (CLI) 初始化有效的 .NET Core 專案和主控台應用程式,然後切換至新建立的資料夾 (mysqlefcore)。

      dotnet new console –o mysqlefcore
      cd mysqlefcore
    2. 使用 dotnet CLI 或 Visual Studio 中的套件管理員主控台,將 MySql.EntityFrameworkCore 套件新增至應用程式。

      dotnet CLI

      輸入下列命令,以新增 MySQL EF Core 7.0 套件,以便與 Connector/NET 8.0.33 及更新版本搭配使用。

      dotnet add package MySql.EntityFrameworkCore --version 7.0.2

      套件管理員主控台

      輸入下列命令,以新增 MySQL EF Core 7.0 套件,以便與 Connector/NET 8.0.33 及更新版本搭配使用。

      Install-Package MySql.EntityFrameworkCore -Version 7.0.2
    3. 還原專案檔案中指定的相依性和專案特定工具,如下所示

      dotnet restore
  2. 建立模型並執行應用程式。

    此範例中的模型將由主控台應用程式使用。它包含在 LibraryContext 類別 (或資料庫內容) 中設定的兩個與圖書館相關的實體。

    1. 建立名為 LibraryModel.cs 的新檔案,然後將下列 BookPublisher 類別新增至 mysqlefcore 命名空間。

      namespace mysqlefcore
      {
        public class Book
        {
          public string ISBN { get; set; }
          public string Title { get; set; }
          public string Author { get; set; }
          public string Language { get; set; }   
          public int Pages { get; set; }
          public virtual Publisher Publisher { get; set; }
        }
      
        public class Publisher
        {
          public int ID { get; set; }
          public string Name { get; set; }
          public virtual ICollection<Book> Books { get; set; }
        }
      }
    2. 建立名為 LibraryContext.cs 的新檔案,並新增下列程式碼。將一般連線字串取代為適合您 MySQL 伺服器設定的字串。

      注意

      MySQL.EntityFrameworkCore.Extensions 命名空間適用於 Connector/NET 8.0.23 及更新版本。較早的連接器版本需要 MySQL.Data.EntityFrameworkCore.Extensions 命名空間。

      using Microsoft.EntityFrameworkCore;
      using MySQL.EntityFrameworkCore.Extensions;
      
      namespace mysqlefcore
      {
        public class LibraryContext : DbContext
        {
          public DbSet<Book> Book { get; set; }
      
          public DbSet<Publisher> Publisher { get; set; }
      
          protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
          {
            optionsBuilder.UseMySQL("server=localhost;database=library;user=user;password=password");
          }
      
          protected override void OnModelCreating(ModelBuilder modelBuilder)
          {
            base.OnModelCreating(modelBuilder);
      
            modelBuilder.Entity<Publisher>(entity =>
            {
              entity.HasKey(e => e.ID);
              entity.Property(e => e.Name).IsRequired();
            });
      
            modelBuilder.Entity<Book>(entity =>
            {
              entity.HasKey(e => e.ISBN);
              entity.Property(e => e.Title).IsRequired();
              entity.HasOne(d => d.Publisher)
                .WithMany(p => p.Books);
            });
          }
        }
      }

      LibraryContex 類別包含要使用的實體,並可設定模型的特定屬性,例如 Key、必要的資料行、參考等等。

    3. 將下列程式碼插入現有的 Program.cs 檔案中,以取代預設的 C# 程式碼。

      using Microsoft.EntityFrameworkCore;
      using System;
      using System.Text;
      
      namespace mysqlefcore
      {
        class Program
        {
          static void Main(string[] args)
          {
            InsertData();
            PrintData();
          }
      
          private static void InsertData()
          {
            using(var context = new LibraryContext())
            {
              // Creates the database if not exists
              context.Database.EnsureCreated();
      
              // Adds a publisher
              var publisher = new Publisher
              {
                Name = "Mariner Books"
              };
              context.Publisher.Add(publisher);
      
              // Adds some books
              context.Book.Add(new Book
              {
                ISBN = "978-0544003415",
                Title = "The Lord of the Rings",
                Author = "J.R.R. Tolkien",
                Language = "English",
                Pages = 1216,
                Publisher = publisher
              });
              context.Book.Add(new Book
              {
                ISBN = "978-0547247762",
                Title = "The Sealed Letter",
                Author = "Emma Donoghue",
                Language = "English",
                Pages = 416,
                Publisher = publisher
              });
      
              // Saves changes
              context.SaveChanges();
            }
          }
      
          private static void PrintData()
          {
            // Gets and prints all books in database
            using (var context = new LibraryContext())
            {
              var books = context.Book
                .Include(p => p.Publisher);
              foreach(var book in books)
              {
                var data = new StringBuilder();
                data.AppendLine($"ISBN: {book.ISBN}");
                data.AppendLine($"Title: {book.Title}");
                data.AppendLine($"Publisher: {book.Publisher.Name}");
                Console.WriteLine(data.ToString());
              }
            }
          }
        }
      }
    4. 使用下列 CLI 命令還原相依性,然後執行應用程式。

      dotnet restore
      dotnet run

執行應用程式的輸出由下列範例表示

ISBN: 978-0544003415
Title: The Lord of the Rings
Publisher: Mariner Books

ISBN: 978-0547247762
Title: The Sealed Letter
Publisher: Mariner Books