跳至頁尾內容
開發者更新

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

在現代軟體開發的領域中,高效的資料管理至關重要。 無論您是在建立一個簡單的應用程式還是一個複雜的企業系統,有效地存取、操作和儲存資料是基本要求。 C#的Entity Framework Core (EF Core) 是一個強大的工具,它通過提供便利且面向物件的方式來簡化資料存取,從而輕鬆處理資料庫。 在本文中,我們將深入探討EF Core的世界,探索其功能、能力和最佳實踐。 此外,我們將看看 IronPDF for Handling PDF Documents 來自 Iron Software Solutions 用以讀取、寫入和管理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物件(POCO)來定義資料模型。 這些實體類代表資料庫表,其屬性映射到表的欄位。

  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. 建立您的應用程式:

    • 通過建立一個Console或ASP.NET應用程式來開始。
  2. 安裝必要的套件:

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

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

    • 定義一個資料庫上下文類(例如,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");
       }
      }
      Public Class DatabaseContext
      	Inherits DbContext
      
       Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
      	 optionsBuilder.UseSqlite("Filename=sample.db")
       End Sub
      End Class
      $vbLabelText   $csharpLabel
  4. 註冊上下文:

    • 在您的Startup類中,將您的上下文新增到服務中:

      public void ConfigureServices(IServiceCollection services)
      {
       services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
      }
      public void ConfigureServices(IServiceCollection services)
      {
       services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
      }
      Public Sub ConfigureServices(ByVal services As IServiceCollection)
       services.AddEntityFrameworkSqlite().AddDbContext(Of DatabaseContext)()
      End Sub
      $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();
       }
      }
      'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
      'ORIGINAL LINE: public Startup(IHostingEnvironment env)
      Public Sub New(ByVal env As IHostingEnvironment)
       Using client = New DatabaseContext()
      	 client.Database.EnsureCreated()
       End Using
      End Sub
      $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 Rendering Engine生成像素完美的PDF。
    • 從 URL、HTML 檔案或 HTML 字串生成 PDF。
  2. 影像和內容轉換:

    • 將影像轉換為和從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; }
    }
}
Imports IronPdf
Imports Microsoft.EntityFrameworkCore
Imports System
Imports System.Linq

Namespace CodeSample
    Public Class Program
        Public Shared Sub Main()
            Console.WriteLine("-------------Demo EF core and IronPDF--------------")

            ' Disable local disk access or cross-origin requests
            Installation.EnableWebSecurity = True

            ' Instantiate Renderer
            Dim renderer = New ChromePdfRenderer()

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

            ' Add Students to Database
            Using client = New DatabaseContext()
                client.Database.EnsureCreated() ' Create table if it doesn't exist
                client.Students.ExecuteDelete() ' Ensure the table is clean

                ' Define students
                Dim students = {
                    New Student With {.StudentName = "Bill", .DateOfBirth = New DateTime(1990, 12, 1), .Height = 5.45D, .Weight = 56, .Grade = 10},
                    New Student With {.StudentName = "Mike", .DateOfBirth = New DateTime(1992, 12, 6), .Height = 4.45D, .Weight = 34, .Grade = 8},
                    New Student With {.StudentName = "Peter", .DateOfBirth = New DateTime(1990, 12, 3), .Height = 5.0D, .Weight = 50, .Grade = 10},
                    New Student With {.StudentName = "Bob", .DateOfBirth = New DateTime(1990, 12, 9), .Height = 4.56D, .Weight = 56, .Grade = 10},
                    New Student With {.StudentName = "Harry", .DateOfBirth = New DateTime(1990, 12, 21), .Height = 5.6D, .Weight = 56, .Grade = 10},
                    New Student With {.StudentName = "Charle", .DateOfBirth = New DateTime(1993, 12, 11), .Height = 5.5D, .Weight = 56, .Grade = 7}
                }

                ' Add students to database
                client.Students.AddRange(students)
                client.SaveChanges()

                ' Add students info to HTML content
                For Each student In students
                    content = AddStudent(content, student)
                Next
            End Using

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

            ' Display Students in Database
            Using client = New DatabaseContext()
                Console.WriteLine("Displaying Students in Database:")
                Dim students = client.Students.ToList()

                For Each student In students
                    Console.WriteLine($"Name= {student.StudentName}, ID={student.StudentID}, Grade={student.Grade}, Weight={student.Weight}, Height={student.Height}")
                    content = AddStudent(content, student)
                Next
            End Using

            ' Render HTML content to PDF
            Dim pdf = renderer.RenderHtmlAsPdf(content)

            ' Export to a file or stream
            pdf.SaveAs("AwesomeEfCoreAndIronPdf.pdf")
        End Sub

        ' Helper method to add student info as HTML content
        Private Shared Function AddStudent(content As String, student As Student) As String
            content += $"<p Name = {student.StudentName}, ID={student.StudentID}, Grade={student.Grade}, Weight={student.Weight}, Height={student.Height}</p>"
            Return content
        End Function
    End Class

    Public Class DatabaseContext
        Inherits DbContext

        Public Property Students As DbSet(Of Student)

        Protected Overrides Sub OnConfiguring(optionsBuilder As DbContextOptionsBuilder)
            optionsBuilder.UseSqlite("Filename=IronPdfDemo.db")
        End Sub
    End Class

    Public Class Student
        Public Property StudentID As Integer
        Public Property StudentName As String
        Public Property DateOfBirth As DateTime?
        Public Property Height As Decimal
        Public Property Weight As Single
        Public Property Grade As Integer
    End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼解釋

  1. 設定渲染器和內容:

    • 程式碼從建立一個含有標題(<h2>)的HTML內容字串開始,用於將學生新增到資料庫。
    • 目標是使用IronPDF生成一個PDF文件,該文件將包含有關學生的資訊。
  2. 資料庫上下文和新增學生:

    • 使用DatabaseContext類與資料庫進行互動。
    • client.Database.EnsureCreated();確保資料庫和表格存在。
    • Students表中的任何現有資料。
    • 定義學生並將其新增到資料庫。 屬性包括Grade
    • client.SaveChanges();將更改儲存到資料庫。
  3. 顯示學生:

    • 使用client.Students.ToList();檢索所有學生。
    • 對於每個學生,打個他們的名字、ID、年級、體重和身高,並將這些資訊新增到HTML內容中。
  4. 渲染到PDF:

    • 實例化ChromePdfRenderer
    • 使用renderer.RenderHtmlAsPdf(content)將HTML內容渲染為PDF。
    • 最終,將PDF保存為"AwesomeEfCoreAndIronPdf.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";
Imports IronPdf

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

可以從 IronPDF Licensing Page 獲得免費試用授權。

結論

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 提供資料庫遷移功能,允許開發者使用程式碼優先的遷移來應用資料庫結構的增量更改,確保資料庫結構與應用程式的資料模型一致。

在EF Core中使用Lazy Loading和Eager Loading有哪些好處?

Lazy Loading 和 Eager Loading 是EF Core中的策略,用來優化資料檢索效能。Lazy Loading在需要時載入相關資料,而Eager Loading則預先檢索相關資料,減少所需查詢的數量。

EF Core如何管理事務?

EF Core 支持顯式的事務管理,確保一系列資料庫操作要麼全部成功,要麼全部失敗,從而在整個過程中保持資料一致性和完整性。

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

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

IronPDF 可以如何與 EF Core 一起使用?

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

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

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

EF Core 如何支持查詢資料?

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

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

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

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話