푸터 콘텐츠로 바로가기
.NET 도움말

Entity Framework Core (How It Works For Developers)

In the realm of modern software development, efficient data management is crucial. Whether you're building a simple application or a complex enterprise system, accessing, manipulating, and saving data effectively is a fundamental requirement. Entity Framework Core (EF Core) in C# is a powerful tool that simplifies data access by providing a convenient and object-oriented approach to working with databases. In this article, we'll delve into the world of EF Core, exploring its features, capabilities, and best practices. Also, we will have a look at IronPDF for Handling PDF Documents from Iron Software Solutions to read, write, and manage PDF documents. We will create a practical example with both packages.

Understanding Entity Framework Core

Entity Framework Core is an open-source, lightweight, and extensible version of the popular Entity Framework data access technology. It's designed to work cross-platform, supporting various existing database server providers including SQL Server, SQLite, MySQL, PostgreSQL, Azure Cosmos DB, and more. EF Core is a modern object database mapper and follows the ORM (Object-Relational Mapping) pattern, allowing developers to work with databases using .NET objects, which eliminates the need for writing tedious SQL queries manually.

Key Features of EF Core

  1. Modeling Entities: EF Core enables developers to define data models using Plain Old CLR Objects (POCOs). These entity classes represent database tables, with properties mapping to table columns.

  2. LINQ Support: EF Core seamlessly supports LINQ queries (Language Integrated Query), allowing developers to write strongly typed queries against the SQL Server or any other database using familiar C# syntax. This makes querying data intuitive and reduces the likelihood of runtime errors. Also, raw SQL statements can be used along with LINQ queries.

  3. Database Migrations: Managing database schema changes can be challenging, especially in a team environment. EF Core simplifies this process by providing database migration capabilities, allowing developers to apply incremental changes to the database schema using code-first migrations.

  4. Lazy Loading and Eager Loading: EF Core supports both lazy loading and eager loading strategies, enabling developers to optimize performance by loading related data on demand or upfront, depending on the use case.

  5. Transaction Management: Transactions ensure data consistency and integrity during database operations. EF Core allows developers to work with transactions explicitly, ensuring that a group of database operations either succeed or fail together.

  6. Concurrency Control: EF Core provides built-in support for managing concurrency conflicts, allowing developers to detect and resolve conflicts that may arise when multiple users attempt to modify the same data simultaneously.

Getting Started with EF Core

Let’s create a basic example of using SQLite with Entity Framework Core (EF Core) in an ASP.NET Core application. Here are the steps:

  1. Create Your Application:

    • Start by creating a Console or ASP.NET application.
  2. Install Necessary Packages:

    • Add the following NuGet packages to your project:

      • Microsoft.EntityFrameworkCore (version 1.0.0 or later)
      • Microsoft.EntityFrameworkCore.Sqlite (version 1.0.0 or later)
  3. Create Your Database Context:

    • Define a class for your database context (e.g., DatabaseContext) that inherits from DbContext.
    • In the OnConfiguring method, set the SQLite connection string:

      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. Register the Context:

    • In your Startup class, add your context to the services:

      public void ConfigureServices(IServiceCollection services)
      {
       services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
      }
      public void ConfigureServices(IServiceCollection services)
      {
       services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
      }
      $vbLabelText   $csharpLabel
  5. Create the Database on Startup:

    • In the Startup constructor, create your database:

      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. Use SQLite in Your Application:

    • Now you can use SQLite in your ASP.NET Core application through EF Core.
    • Define your models and use the DatabaseContext to interact with the database.

Remember that this is a basic example, and there are other ways to configure the connection string and use EF Core. Feel free to explore more advanced features and adapt this to your specific needs!

Best Practices for EF Core Development

  1. Keep DbContext Scoped: DbContext instances in EF Core are designed to be short-lived and should typically be scoped to the lifetime of a single request in web applications.

  2. Use AsNoTracking for Read-Only Operations: When performing read-only operations where entities are not expected to be modified, use the AsNoTracking method to improve performance by bypassing change tracking.

  3. Optimize Queries: Write efficient queries by using appropriate indexing, pagination, and filtering techniques to minimize the amount of data retrieved from the database.

  4. Avoid N+1 Query Problems: Be mindful of the N+1 query problem, where a query is executed for each related entity in a collection. Use eager loading or explicit loading to fetch related data efficiently.

  5. Monitor Performance: Monitor EF Core performance using tools like Entity Framework Profiler or built-in logging capabilities to identify and address performance bottlenecks.

Introduction to IronPDF

Entity Framework Core (How It Works For Developers): Figure 1 - IronPDF

IronPDF is a powerful C# PDF library that allows you to generate, edit, and extract content from PDF documents in .NET projects. Here are some key features:

  1. HTML to PDF Conversion:

    • Convert HTML, CSS, and JavaScript content to PDF format.
    • Use the Chrome Rendering Engine for pixel-perfect PDFs.
    • Generate PDFs from URLs, HTML files, or HTML strings.
  2. Image and Content Conversion:

    • Convert images to and from PDF.
    • Extract text and images from existing PDFs.
    • Support for various image formats.
  3. Editing and Manipulation:

    • Set properties, security, and permissions for PDFs.
    • Add digital signatures.
    • Edit metadata and revision history.
  4. Cross-Platform Support:

    • Works with .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+).
    • Compatible with Windows, Linux, and macOS.
    • Available on NuGet for easy installation.

Generate PDF document using IronPDF along with EF Core

To start with, create a Console application using Visual Studio as below.

Entity Framework Core (How It Works For Developers): Figure 2 - New Project

Provide Project Name.

Entity Framework Core (How It Works For Developers): Figure 3 - Project Configuration

Provide .NET cross platform version.

Entity Framework Core (How It Works For Developers): Figure 4 - Framework

Install Microsoft.EntityFrameworkCore package.

Entity Framework Core (How It Works For Developers): Figure 5 - Microsoft.EntityFrameworkCore package

Install Microsoft.EntityFrameworkCore.SqlLite package.

Entity Framework Core (How It Works For Developers): Figure 6 - Microsoft.EntityFrameworkCore.SqlLite package

Install IronPDF package.

Entity Framework Core (How It Works For Developers): Figure 7 - IronPDF

Add below code to 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

Code Explanation

  1. Setting Up the Renderer and Content:

    • The code begins by creating an HTML content string with a heading (<h1>) and subheading (<h2>) for adding students to the database.
    • The goal is to generate a PDF document using IronPDF, which will include information about the students.
  2. Database Context and Adding Students:

    • The DatabaseContext class is used to interact with the database.
    • client.Database.EnsureCreated(); ensures that the database and the table exist.
    • client.Students.ExecuteDelete(); clears any existing data from the Students table.
    • Students are defined and added to the database. The properties include StudentName, DateOfBirth, Height, Weight, and Grade.
    • client.SaveChanges(); saves the changes to the database.
  3. Displaying Students:

    • The code retrieves all students using client.Students.ToList();.
    • For each student, it prints their name, ID, grade, weight, and height and adds this information to the HTML content.
  4. Rendering to PDF:

    • The ChromePdfRenderer is instantiated.
    • The HTML content is rendered into a PDF using renderer.RenderHtmlAsPdf(content).
    • Finally, the PDF is saved as "AwesomeEfCoreAndIronPdf.pdf".

Output

Entity Framework Core (How It Works For Developers): Figure 8 - Console Output

PDF

Entity Framework Core (How It Works For Developers): Figure 9 - PDF Output

IronPDF Licensing

IronPDF package requires a license to run and generate the PDF. Add the below code at the start of the application before the package is accessed.

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

A trial license is available from the IronPDF Licensing Page.

Conclusion

Entity Framework Core in C# provides a robust and intuitive way to interact with databases, offering features like LINQ support, database migrations, and transaction management out of the box. By following best practices and leveraging its powerful capabilities, developers can build scalable and maintainable applications with ease. Whether you're a seasoned developer or just getting started, EF Core is a valuable tool to have in your toolkit for modern data access in C# applications. On the other hand, IronPDF is a .NET library for creating, manipulating, and rendering PDF documents within your applications. You can use it along with EF Core to convert HTML content (including images) into a PDF file.

자주 묻는 질문

엔티티 프레임워크 코어란 무엇이며 왜 유용한가요?

엔티티 프레임워크 코어(EF Core)는 개발자가 .NET 개체를 사용하여 데이터베이스와 상호 작용할 수 있도록 하여 수동 SQL 쿼리가 필요 없도록 데이터 액세스를 간소화하는 오픈 소스 경량 ORM(객체 관계형 매핑) 도구입니다.

.NET 프로젝트에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

.NET 라이브러리인 IronPDF를 사용하여 데이터베이스에서 검색된 데이터를 포함한 HTML 콘텐츠를 PDF 파일로 변환할 수 있습니다. 이를 통해 C# 애플리케이션에서 데이터 처리와 문서 생성을 원활하게 통합할 수 있습니다.

EF Core는 데이터베이스 마이그레이션을 어떻게 처리하나요?

EF Core는 개발자가 코드 우선 마이그레이션을 사용하여 데이터베이스 스키마에 점진적인 변경 사항을 적용하여 데이터베이스 구조가 애플리케이션의 데이터 모델과 일치하도록 보장하는 데이터베이스 마이그레이션 기능을 제공합니다.

EF Core에서 지연 로딩과 에저 로딩을 사용하면 어떤 이점이 있나요?

지연 로딩과 조속 로딩은 데이터 검색 성능을 최적화하기 위한 EF Core의 전략입니다. 지연 로딩은 필요할 때 관련 데이터를 로드하는 반면, 빠른 로딩은 관련 데이터를 미리 검색하여 필요한 쿼리 횟수를 줄입니다.

EF Core는 트랜잭션을 어떻게 관리하나요?

EF Core는 명시적인 트랜잭션 관리를 지원하여 일련의 데이터베이스 작업이 모두 성공하거나 모두 함께 실패하도록 보장함으로써 프로세스 전반에 걸쳐 데이터 일관성과 무결성을 유지합니다.

EF Core를 사용하기 위한 모범 사례는 무엇인가요?

EF Core의 모범 사례에는 단일 요청으로 범위가 제한된 DbContext 인스턴스 유지, 읽기 전용 작업에 AsNoTracking을 사용하여 성능 향상, 쿼리 최적화, N+1 쿼리 문제 방지 등이 포함됩니다.

IronPDF는 EF Core와 함께 어떻게 사용할 수 있나요?

IronPDF는 EF Core와 함께 사용하여 EF Core에서 관리하는 데이터베이스의 데이터를 포함한 HTML 콘텐츠로부터 PDF 문서를 생성할 수 있습니다. 이 조합을 통해 .NET 애플리케이션 내에서 효율적인 데이터 관리 및 문서 생성이 가능합니다.

프로젝트에서 PDF 생성을 위해 .NET 라이브러리를 사용하려면 무엇이 필요합니까?

IronPDF를 사용하려면 NuGet을 통해 IronPDF 패키지를 설치하고 유효한 라이선스 키가 있어야 합니다. 평가판 라이선스는 IronPDF 라이선스 페이지에서 사용할 수 있습니다.

EF Core는 데이터 쿼리를 어떻게 지원하나요?

EF Core는 LINQ 쿼리를 지원하므로 개발자가 C# 구문을 사용하여 강력하게 입력된 쿼리를 작성할 수 있습니다. 또한 보다 복잡한 데이터 작업을 위한 원시 SQL 문도 실행할 수 있습니다.

.NET 애플리케이션에서 EF Core를 시작하려면 어떻게 해야 하나요?

EF Core 사용을 시작하려면 콘솔 또는 ASP.NET 애플리케이션을 설정하고, Microsoft.EntityFrameworkCore와 같은 필요한 NuGet 패키지를 설치하고, 데이터 모델을 정의하고, 데이터베이스 연결을 구성하고, 데이터 작업 관리를 위한 DbContext를 생성합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.