跳過到頁腳內容
.NET幫助

Entity Framework Core(對開發者如何理解的工作)

在現代軟體開發的領域,效率高的資料管理至關重要。 無論您是在構建一個簡單的應用程式還是複雜的企業系統,有效地訪問、操作和保存資料是基本要求。 C#中的Entity Framework Core(EF Core)是一個強大的工具,通過提供一種方便的面向物件的方法來簡化資料訪問。 在本文中,我們將深入討論EF Core,探索其功能、能力及最佳實踐。 此外,我們還將查看Iron Software Solutions的IronPDF for Handling PDF Documents,用於閱讀、撰寫和管理PDF文件。 我們將使用這兩個套件來創建一個實用的例子。

理解Entity Framework Core

Entity Framework Core是一個開源、輕量且可擴展的版本,是流行的Entity Framework資料訪問技術。 它被設計為跨平台工作,支援各種現有的資料庫伺服器提供商,包括SQL Server、SQLite、MySQL、PostgreSQL、Azure Cosmos DB等。 EF Core是一個現代的物件資料庫映射器,遵循ORM(物件關聯映射)模式,允許開發者使用.NET物件來處理資料庫,這消除了手動編寫繁瑣的SQL查詢的需求。

EF Core的主要特點

  1. 建模實體: EF Core允許開發者使用簡單的CLR物件(POCOs)來定義資料模型。 這些實體類別代表資料庫表,其中屬性對應表中的列。

  2. LINQ支援: EF Core無縫支援LINQ查詢(語言集成查詢),允許開發者使用熟悉的C#語法針對SQL Server或其他任何資料庫撰寫強類型查詢。 這使得查詢資料更加直觀,並減少運行時錯誤的可能性。 此外,可以將原始SQL語句與LINQ查詢一起使用。

  3. 資料庫遷移: 在團隊環境中,管理資料庫結構的變更可能是具有挑戰性的。 EF Core通過提供資料庫遷移功能來簡化這個過程,允許開發者使用代碼優先遷移將增量更改應用到資料庫結構。

  4. 延遲加載和提前加載: EF Core支援延遲加載和提前加載策略,允許開發者根據使用情況按需或在使用前加載相關資料以優化性能。

  5. 事務管理: 事務在資料庫操作期間確保資料的一致性和完整性。 EF Core允許開發者明確地使用事務,確保一組資料庫操作要麼成功,要麼一起失敗。

  6. 併發控制: EF Core提供內建支持來管理併發衝突,允許開發者檢測和解決多個使用者試圖同時修改相同資料時可能產生的衝突。

開始使用EF Core

讓我們創建一個基本示例,演示如何在ASP.NET Core應用程式中使用SQLite和Entity Framework Core(EF Core)。 以下是步驟:

  1. 創建您的應用程式:

    • 首先創建一個控制台或ASP.NET應用程式。
  2. 安裝必要的套件:

    • 將以下NuGet套件新增到您的專案中:

      • Microsoft.EntityFrameworkCore(版本1.0.0或更高)
      • Microsoft.EntityFrameworkCore.Sqlite(版本1.0.0或更高)
  3. 創建您的資料庫上下文:

    • 定義一個class作為您的資料庫上下文(例如,DbContext
    • OnConfiguring方法中設置SQLite連接字串:

      public class DatabaseContext : DbContext
      {
       protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
       {
           optionsBuilder.UseSqlite("Filename=sample.db");
       }
      }
      public class DatabaseContext : DbContext
      {
       protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
       {
           optionsBuilder.UseSqlite("Filename=sample.db");
       }
      }
      $vbLabelText   $csharpLabel
  4. 註冊上下文:

    • 在您的Startupclass中,將您的上下文添加到服務中:

      public void ConfigureServices(IServiceCollection services)
      {
       services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
      }
      public void ConfigureServices(IServiceCollection services)
      {
       services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
      }
      $vbLabelText   $csharpLabel
  5. 在啟動時創建資料庫:

    • Startup構造函數中創建您的資料庫:

      public Startup(IHostingEnvironment env)
      {
       using (var client = new DatabaseContext())
       {
           client.Database.EnsureCreated();
       }
      }
      public Startup(IHostingEnvironment env)
      {
       using (var client = new DatabaseContext())
       {
           client.Database.EnsureCreated();
       }
      }
      $vbLabelText   $csharpLabel
  6. 在您的應用程式中使用SQLite:

    • 現在您可以通過EF Core在您的ASP.NET Core應用程式中使用SQLite。
    • 定義您的模型並使用DatabaseContext與資料庫進行交互。

請記住,這是一個基本示例,還有其他方式可以配置連接字串並使用EF Core。 隨時探索更多高級功能,並根據您的特定需求進行調整!

EF Core開發的最佳實踐

  1. 保持DbContext範圍:EF Core中的DbContext實例設計為短暫的,通常應該限定在web應用程式中單個請求的生命週期內。

  2. 對於只讀操作使用AsNoTracking:在執行只讀操作時,如果不期望實體被修改,請使用AsNoTracking方法,以通過繞過變更跟踪來提高性能。

  3. 優化查詢:透過使用適當的索引、分頁和篩選技術撰寫有效查詢,以最小化從資料庫檢索的資料量。

  4. 避免N+1查詢問題:注意N+1查詢問題,在合集中的每個相關實體上執行查詢。 使用提前加載或明確加載來有效地獲取相關資料。

  5. 監控性能:使用Entity Framework Profiler或內建的日誌功能等工具監控EF Core性能,以識別和解決性能瓶頸。

IronPDF 簡介

Entity Framework Core(開發人員如何運作):圖1 - IronPDF

IronPDF是一個強大的C# PDF程式庫,可讓您在.NET專案中生成、編輯和提取PDF文件的內容。 以下是一些主要功能:

  1. HTML 至 PDF 轉換:

    • 將HTML、CSS和JavaScript內容轉換為PDF格式。
    • 使用Chrome渲染引擎以獲得像素完美的PDF。
    • 從 URL、HTML 檔案或 HTML 字串生成 PDF。
  2. 圖片和內容轉換:

    • 將圖像轉換為PDF,或從PDF中提取圖像。
    • 從現有的PDF中提取文本和圖像。
    • 支援各種圖像格式。
  3. 編輯和操控:

    • 為PDF設置屬性、安全性和權限。
    • 添加數字簽名。
    • 編輯元數據及修訂歷史。
  4. 跨平台支援:

    • 適用於 .NET Core (8、7、6、5 和 3.1+),.NET Standard (2.0+),以及 .NET Framework (4.6.2+)。
    • 相容於 Windows、Linux 和 macOS。
    • 可在 NuGet 上找到,方便安裝。

使用IronPDF與EF Core生成PDF文件

首先,使用 Visual Studio 創建一個主控台應用程式,如下所示。

Entity Framework Core(開發人員如何運作):圖2 - 新專案

提供專案名稱。

Entity Framework Core(開發人員如何運作):圖3 - 專案配置

提供.NET跨平台版本。

Entity Framework Core(開發人員如何運作):圖4 - 框架

安裝Microsoft.EntityFrameworkCore套件。

Entity Framework Core(開發人員如何運作):圖5 - Microsoft.EntityFrameworkCore套件

安裝Microsoft.EntityFrameworkCore.SqlLite套件。

Entity Framework Core(開發人員如何運作):圖6 - Microsoft.EntityFrameworkCore.SqlLite套件

安裝IronPDF套件。

Entity Framework Core(開發人員如何運作):圖7 - IronPDF

將以下代碼添加到Program.cs

using IronPdf;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace CodeSample
{
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("-------------Demo EF core and IronPDF--------------");

            // Disable local disk access or cross-origin requests
            Installation.EnableWebSecurity = true;

            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();

            // Start with initial HTML content
            var content = "<h1>Demo EF core and IronPDF</h1>";
            content += "<h2>Add Students</h2>";

            // Add Students to Database
            using (var client = new DatabaseContext())
            {
                client.Database.EnsureCreated(); // Create table if it doesn't exist
                client.Students.ExecuteDelete(); // Ensure the table is clean

                // Define students
                var students = new[]
                {
                    new Student { StudentName = "Bill", DateOfBirth = new DateTime(1990, 12, 01), Height = 5.45M, Weight = 56, Grade = 10 },
                    new Student { StudentName = "Mike", DateOfBirth = new DateTime(1992, 12, 06), Height = 4.45M, Weight = 34, Grade = 8 },
                    new Student { StudentName = "Peter", DateOfBirth = new DateTime(1990, 12, 03), Height = 5.0M, Weight = 50, Grade = 10 },
                    new Student { StudentName = "Bob", DateOfBirth = new DateTime(1990, 12, 09), Height = 4.56M, Weight = 56, Grade = 10 },
                    new Student { StudentName = "Harry", DateOfBirth = new DateTime(1990, 12, 21), Height = 5.6M, Weight = 56, Grade = 10 },
                    new Student { StudentName = "Charle", DateOfBirth = new DateTime(1993, 12, 11), Height = 5.5M, Weight = 56, Grade = 7 }
                };

                // Add students to database
                client.Students.AddRange(students);
                client.SaveChanges();

                // Add students info to HTML content
                foreach (var student in students)
                {
                    content = AddStudent(content, student);
                }
            }

            content += "<h2>Display Students in Database</h2>";

            // Display Students in Database
            using (var client = new DatabaseContext())
            {
                Console.WriteLine($"Displaying Students in Database:");
                var students = client.Students.ToList();

                foreach (var student in students)
                {
                    Console.WriteLine($"Name= {student.StudentName}, ID={student.StudentID}, Grade={student.Grade}, Weight={student.Weight}, Height={student.Height}");
                    content = AddStudent(content, student);
                }
            }           

            // Render HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Export to a file or stream
            pdf.SaveAs("AwesomeEfCoreAndIronPdf.pdf");
        }

        // Helper method to add student info as HTML content
        private static string AddStudent(string content, Student student)
        {
            content += $"<p Name = {student.StudentName}, ID={student.StudentID}, Grade={student.Grade}, Weight={student.Weight}, Height={student.Height}</p>";
            return content;
        }
    }

    public class DatabaseContext : DbContext
    {
        public DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Filename=IronPdfDemo.db");
        }        
    }

    public class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public decimal Height { get; set; }
        public float Weight { get; set; }
        public int Grade { get; set; }
    }
}
using IronPdf;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace CodeSample
{
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("-------------Demo EF core and IronPDF--------------");

            // Disable local disk access or cross-origin requests
            Installation.EnableWebSecurity = true;

            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();

            // Start with initial HTML content
            var content = "<h1>Demo EF core and IronPDF</h1>";
            content += "<h2>Add Students</h2>";

            // Add Students to Database
            using (var client = new DatabaseContext())
            {
                client.Database.EnsureCreated(); // Create table if it doesn't exist
                client.Students.ExecuteDelete(); // Ensure the table is clean

                // Define students
                var students = new[]
                {
                    new Student { StudentName = "Bill", DateOfBirth = new DateTime(1990, 12, 01), Height = 5.45M, Weight = 56, Grade = 10 },
                    new Student { StudentName = "Mike", DateOfBirth = new DateTime(1992, 12, 06), Height = 4.45M, Weight = 34, Grade = 8 },
                    new Student { StudentName = "Peter", DateOfBirth = new DateTime(1990, 12, 03), Height = 5.0M, Weight = 50, Grade = 10 },
                    new Student { StudentName = "Bob", DateOfBirth = new DateTime(1990, 12, 09), Height = 4.56M, Weight = 56, Grade = 10 },
                    new Student { StudentName = "Harry", DateOfBirth = new DateTime(1990, 12, 21), Height = 5.6M, Weight = 56, Grade = 10 },
                    new Student { StudentName = "Charle", DateOfBirth = new DateTime(1993, 12, 11), Height = 5.5M, Weight = 56, Grade = 7 }
                };

                // Add students to database
                client.Students.AddRange(students);
                client.SaveChanges();

                // Add students info to HTML content
                foreach (var student in students)
                {
                    content = AddStudent(content, student);
                }
            }

            content += "<h2>Display Students in Database</h2>";

            // Display Students in Database
            using (var client = new DatabaseContext())
            {
                Console.WriteLine($"Displaying Students in Database:");
                var students = client.Students.ToList();

                foreach (var student in students)
                {
                    Console.WriteLine($"Name= {student.StudentName}, ID={student.StudentID}, Grade={student.Grade}, Weight={student.Weight}, Height={student.Height}");
                    content = AddStudent(content, student);
                }
            }           

            // Render HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Export to a file or stream
            pdf.SaveAs("AwesomeEfCoreAndIronPdf.pdf");
        }

        // Helper method to add student info as HTML content
        private static string AddStudent(string content, Student student)
        {
            content += $"<p Name = {student.StudentName}, ID={student.StudentID}, Grade={student.Grade}, Weight={student.Weight}, Height={student.Height}</p>";
            return content;
        }
    }

    public class DatabaseContext : DbContext
    {
        public DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Filename=IronPdfDemo.db");
        }        
    }

    public class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public decimal Height { get; set; }
        public float Weight { get; set; }
        public int Grade { get; set; }
    }
}
$vbLabelText   $csharpLabel

程式碼說明

  1. 設置渲染器和內容:

    • 程式碼首先創建了一個包含標題(<h2>)的HTML內容字串,用於將學生新增到資料庫中。
    • 目標是使用IronPDF生成一個PDF文件,其中將包含學生的資訊。
  2. 資料庫上下文和新增學生:

    • DatabaseContext類用於與資料庫交互。
    • client.Database.EnsureCreated();確保資料庫和表存在。
    • Students表中的任何現有數據。
    • 定義並新增學生到資料庫中。 這些屬性包括StudentName, DateOfBirth, Height, Grade
    • client.SaveChanges();將更改保存到資料庫。
  3. 顯示學生:

    • 程式碼使用client.Students.ToList();檢索所有學生。
    • 對於每位學生,它會打印他們的姓名、ID、成績、體重和身高,並將這些信息新增到HTML內容中。
  4. 渲染為PDF:

    • 初始化ChromePdfRenderer
    • 使用renderer.RenderHtmlAsPdf(content)將HTML內容渲染為PDF。
    • 最後,PDF被保存為"AwsomeEFCoreAndIronPdf.pdf"。

輸出

Entity Framework Core(開發人員如何運作):圖8 - 控制台輸出

PDF

Entity Framework Core(開發人員如何運作):圖9 - PDF輸出

IronPDF 授權

IronPDF套件需要授權才能運行和生成PDF。 在應用程式開始時,在訪問軟體包之前添加以下程式碼。

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
$vbLabelText   $csharpLabel

試用授權可從IronPDF授權頁面獲得。

結論

C#中的Entity Framework Core為與資料庫交互提供了一種強大且直觀的方式,內建功能包括LINQ支援、資料庫遷移和事務管理。 透過遵循最佳實踐並利用其強大的能力,開發者可以輕鬆構建可擴展且易於維護的應用程式。 無論您是一位經驗豐富的開發者還是剛剛起步,EF Core都是您C#應用程式現代資料訪問工具包中的一個有價值的工具。 另一方面,IronPDF是一個.NET程式庫,用於在您的應用程式中創建、操作和渲染PDF文件。 您可以將它與EF Core一起使用,將HTML內容(包括圖片)轉換成PDF文件。

常見問題解答

什麼是Entity Framework Core,它為什麼有用?

Entity Framework Core(EF Core)是一種開源的輕量級ORM(物件關聯映射)工具,可以讓開發人員透過.NET物件與資料庫交互,簡化資料存取,消除手動編寫SQL查詢的需要。

如何在.NET專案中將HTML內容轉換為PDF?

您可以使用IronPDF,一個.NET函式庫,將HTML內容(包括從資料庫檢索的資料)轉換為PDF文件。它允許在C#應用程式中無縫整合資料處理與文件生成。

EF Core如何處理資料庫遷移?

EF Core提供資料庫遷移功能,允許開發人員利用code-first遷移以累加方式對資料庫架構進行更改,確保資料庫結構與應用程式的資料模型對齊。

使用EF Core中的延遲載入和預先載入有什麼好處?

延遲載入和預先載入是EF Core中用來優化資料檢索效能的策略。延遲載入按需載入相關資料,而預先載入則提前檢索相關資料以減少所需查詢數量。

EF Core如何管理交易?

EF Core支持顯式交易管理,確保一系列資料庫操作要么全部成功,要么全部失敗,從而在整個過程中維持資料的穩定性和完整性。

使用EF Core的最佳實踐是什麼?

EF Core的最佳實踐包括將DbContext實例範圍限於單一請求,對於唯讀操作使用AsNoTracking以提高性能,優化查詢並避免N+1查詢問題。

如何將IronPDF與EF Core一起使用?

IronPDF可以與EF Core一起使用,用於將HTML內容(包括EF Core管理的資料庫資料)生成PDF文件。此組合允許在.NET應用程式中進行高效的資料管理和文件生成。

在專案中使用.NET函式庫生成PDF需要什麼?

要使用IronPDF,您需要透過NuGet安裝IronPDF套件並擁有有效的授權金鑰。試用授權可以從IronPDF Licensing Page獲得。

EF Core如何支持資料查詢?

EF Core支持LINQ查詢,允許開發人員使用C#語法撰寫強類型查詢。它還允許執行原始SQL語句以進行更複雜的資料操作。

如何在.NET應用程式中開始使用EF Core?

要開始使用EF Core,請設置一個Console或ASP.NET應用程式,安裝必要的NuGet套件,如Microsoft.EntityFrameworkCore,定義資料模型,配置資料庫連接,並創建DbContext以管理資料操作。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me