.NET HELP

Entity Framework Core (How It Works For Developers)

Published August 13, 2024
Share:

Introduction

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 from IronSoftware 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");
          }
      }
      IRON VB CONVERTER ERROR developers@ironsoftware.com
      VB   C#
  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>();
      }
      IRON VB CONVERTER ERROR developers@ironsoftware.com
      VB   C#
  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();
          }
      }
      IRON VB CONVERTER ERROR developers@ironsoftware.com
      VB   C#
  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 Microsoft.EntityFrameworkCore;
using System.Xml.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();
            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
                client.Students.ExecuteDelete(); // ensure clean table
                var stud1 = new Student { StudentName = "Bill", DateOfBirth = new DateTime(1990, 12, 01), Height = 5.45M, Weight = 56, Grade = 10 };
                content = AddStudent(content, stud1);
                var stud2 = new Student { StudentName = "Mike", DateOfBirth = new DateTime(1992, 12, 06), Height = 4.45M, Weight = 34, Grade = 8 };
                content = AddStudent(content, stud2);
                var stud3 = new Student { StudentName = "Peter", DateOfBirth = new DateTime(1990, 12, 03), Height = 5.0M, Weight = 50, Grade = 10 };
                content = AddStudent(content, stud3);
                var stud4 = new Student { StudentName = "Bob", DateOfBirth = new DateTime(1990, 12, 09), Height = 4.56M, Weight = 56, Grade = 10 };
                content = AddStudent(content, stud4);
                var stud5 = new Student { StudentName = "Harry", DateOfBirth = new DateTime(1990, 12, 21), Height = 5.6M, Weight = 56, Grade = 10 };
                content = AddStudent(content, stud5);
                var stud6 = new Student { StudentName = "Charle", DateOfBirth = new DateTime(1993, 12, 11), Height = 5.5M, Weight = 56, Grade = 7 };
                content = AddStudent(content, stud6);
                client.Students.Add(stud1);
                client.Students.Add(stud2);
                client.Students.Add(stud3);
                client.Students.Add(stud4);
                client.Students.Add(stud5);
                client.Students.Add(stud6);
                client.SaveChanges();
            }
            content += "<h2>Display Students in Database</h2>";
            // Display Students in Database
            using (var client = new DatabaseContext())
            {
                Console.WriteLine($"Display Stduents in Database");
                var students = client.Students.ToList();
                foreach (var student in students)
                {
                    Console.WriteLine($"Name= {student.StudentName},ID={student.StudentID},G={student.Grade},W={student.Weight},H={student.Height}");
                    content = AddStudent(content, student);
                }
            }           
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeEfCoreAndIronPdf.pdf");
        }
        private static string AddStudent(string content, Student student)
        {
            content += $"<p>Name = {student.StudentName},ID={student.StudentID},G={student.Grade},W={student.Weight},H={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 Microsoft.EntityFrameworkCore;
using System.Xml.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();
            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
                client.Students.ExecuteDelete(); // ensure clean table
                var stud1 = new Student { StudentName = "Bill", DateOfBirth = new DateTime(1990, 12, 01), Height = 5.45M, Weight = 56, Grade = 10 };
                content = AddStudent(content, stud1);
                var stud2 = new Student { StudentName = "Mike", DateOfBirth = new DateTime(1992, 12, 06), Height = 4.45M, Weight = 34, Grade = 8 };
                content = AddStudent(content, stud2);
                var stud3 = new Student { StudentName = "Peter", DateOfBirth = new DateTime(1990, 12, 03), Height = 5.0M, Weight = 50, Grade = 10 };
                content = AddStudent(content, stud3);
                var stud4 = new Student { StudentName = "Bob", DateOfBirth = new DateTime(1990, 12, 09), Height = 4.56M, Weight = 56, Grade = 10 };
                content = AddStudent(content, stud4);
                var stud5 = new Student { StudentName = "Harry", DateOfBirth = new DateTime(1990, 12, 21), Height = 5.6M, Weight = 56, Grade = 10 };
                content = AddStudent(content, stud5);
                var stud6 = new Student { StudentName = "Charle", DateOfBirth = new DateTime(1993, 12, 11), Height = 5.5M, Weight = 56, Grade = 7 };
                content = AddStudent(content, stud6);
                client.Students.Add(stud1);
                client.Students.Add(stud2);
                client.Students.Add(stud3);
                client.Students.Add(stud4);
                client.Students.Add(stud5);
                client.Students.Add(stud6);
                client.SaveChanges();
            }
            content += "<h2>Display Students in Database</h2>";
            // Display Students in Database
            using (var client = new DatabaseContext())
            {
                Console.WriteLine($"Display Stduents in Database");
                var students = client.Students.ToList();
                foreach (var student in students)
                {
                    Console.WriteLine($"Name= {student.StudentName},ID={student.StudentID},G={student.Grade},W={student.Weight},H={student.Height}");
                    content = AddStudent(content, student);
                }
            }           
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeEfCoreAndIronPdf.pdf");
        }
        private static string AddStudent(string content, Student student)
        {
            content += $"<p>Name = {student.StudentName},ID={student.StudentID},G={student.Grade},W={student.Weight},H={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; }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Code Explanation

  1. Setting Up the Renderer and Content:

    • The code begins by creating an HTML content string. It starts with a heading

      and adds a subheading

      for adding students to the database.

    • The goal seems to be generating a PDF document using IronPDF, which will include information about students.
  2. Database Context and Adding Students:

    • The DatabaseContext class is used to interact with the database.

    • client.Database.EnsureCreated(); ensures that the database table exists.

    • client.Students.ExecuteDelete(); clears any existing data from the Students table.

    • A new student (stud1) is created with properties like StudentName, DateOfBirth, Height, Weight, and Grade.

    • client.Students.Add(stud1); adds this student to the database.
    • client.SaveChanges(); saves the changes to the database.
  3. Displaying Students:

    • The code then displays the students in the database.

    • It retrieves all students using client.Students.ToList();.

    • For each student, it prints their name, ID, grade, weight, and height.
    • Additionally, the AddStudent function is called (not shown in this snippet).
  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 license to run and generate the PDF. Add 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
VB   C#

Trial License is available here.

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 PDF file.

< PREVIOUS
AutoFixture C# (How It Works For Developers)
NEXT >
FluentEmail C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >