Saltar al pie de página
.NET AYUDA

Entity Framework Core (Cómo Funciona para Desarrolladores)

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");
       }
      }
      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. 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>();
      }
      Public Sub ConfigureServices(ByVal services As IServiceCollection)
       services.AddEntityFrameworkSqlite().AddDbContext(Of DatabaseContext)()
      End Sub
      $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();
       }
      }
      '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. 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; }
    }
}
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, 01),
						.Height = 5.45D,
						.Weight = 56,
						.Grade = 10
					},
					New Student With {
						.StudentName = "Mike",
						.DateOfBirth = New DateTime(1992, 12, 06),
						.Height = 4.45D,
						.Weight = 34,
						.Grade = 8
					},
					New Student With {
						.StudentName = "Peter",
						.DateOfBirth = New DateTime(1990, 12, 03),
						.Height = 5.0D,
						.Weight = 50,
						.Grade = 10
					},
					New Student With {
						.StudentName = "Bob",
						.DateOfBirth = New DateTime(1990, 12, 09),
						.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 student
			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 student
			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(ByVal content As String, ByVal 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(ByVal 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

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";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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.

Preguntas Frecuentes

¿Qué es Entity Framework Core y por qué es útil?

Entity Framework Core (EF Core) es una herramienta ORM (Mapeo Objeto-Relacional) de código abierto y liviana que simplifica el acceso a datos al permitir a los desarrolladores interactuar con bases de datos usando objetos .NET, eliminando la necesidad de consultas SQL manuales.

¿Cómo puedo convertir contenido HTML a PDF en un proyecto .NET?

Puedes usar IronPDF, una biblioteca de .NET, para convertir contenido HTML, incluyendo datos recuperados de una base de datos, en un archivo PDF. Permite una integración sin problemas del manejo de datos y la generación de documentos en aplicaciones C#.

¿Cómo maneja EF Core las migraciones de bases de datos?

EF Core ofrece capacidades de migración de bases de datos, lo que permite a los desarrolladores aplicar cambios incrementales al esquema de la base de datos usando migraciones orientadas al código, asegurando que la estructura de la base de datos se alinee con los modelos de datos de la aplicación.

¿Cuáles son los beneficios de usar carga diferida (lazy loading) y carga temprana (eager loading) en EF Core?

La carga diferida y la carga temprana son estrategias en EF Core para optimizar el rendimiento de la recuperación de datos. La carga diferida carga los datos relacionados a demanda, mientras que la carga temprana recupera los datos relacionados de antemano, reduciendo el número de consultas requeridas.

¿Cómo maneja EF Core las transacciones?

EF Core admite la gestión explícita de transacciones, asegurando que una serie de operaciones de base de datos o todas tengan éxito o todas fallen juntas, manteniendo así la consistencia e integridad de los datos a lo largo del proceso.

¿Cuáles son algunas prácticas recomendadas para usar EF Core?

Las mejores prácticas para EF Core incluyen mantener las instancias de DbContext limitadas a una única solicitud, usar AsNoTracking para operaciones de solo lectura para mejorar el rendimiento, optimizar las consultas y evitar el problema de las consultas N+1.

¿Cómo puede utilizarse IronPDF junto con EF Core?

IronPDF puede usarse junto con EF Core para generar documentos PDF a partir de contenido HTML, incluyendo datos de una base de datos gestionada por EF Core. Esta combinación permite una gestión eficiente de datos y generación de documentos dentro de aplicaciones .NET.

¿Qué se requiere para usar una biblioteca .NET para generación de PDF en un proyecto?

Para usar IronPDF, necesitas instalar el paquete IronPDF a través de NuGet y tener una clave de licencia válida. Una licencia de prueba está disponible en la página de licencias de IronPDF.

¿Cómo admite EF Core la consulta de datos?

EF Core admite consultas LINQ, permitiendo a los desarrolladores escribir consultas fuertemente tipadas usando la sintaxis de C#. También permite la ejecución de sentencias SQL en bruto para operaciones de datos más complejas.

¿Cómo puedes comenzar con EF Core en una aplicación .NET?

Para comenzar a usar EF Core, configura una aplicación de Consola o ASP.NET, instala los paquetes NuGet necesarios como Microsoft.EntityFrameworkCore, define tus modelos de datos, configura la conexión a la base de datos y crea un DbContext para gestionar las operaciones de datos.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más