Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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 IronSoftware Solutions to read, write, and manage PDF documents. We will create a practical example with both packages.
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.
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.
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.
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.
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.
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.
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:
Create Your Application:
Install Necessary Packages:
Add the following NuGet packages to your project:
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
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
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
Use SQLite in Your Application:
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!
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.
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.
Optimize Queries: Write efficient queries by using appropriate indexing, pagination, and filtering techniques to minimize the amount of data retrieved from the database.
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.
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:
HTML to PDF Conversion:
Convert HTML, CSS, and JavaScript content to PDF format.
Image and Content Conversion:
Convert images to and from PDF.
Editing and Manipulation:
Set properties, security, and permissions for PDFs.
Cross-Platform Support:
Works with .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+).
To start with, create a Console application using Visual Studio as below.
Provide Project Name.
Provide .NET cross platform version.
Install Microsoft.EntityFrameworkCore package.
Install Microsoft.EntityFrameworkCore.SqlLite package.
Install IronPDF package.
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
Setting Up the Renderer and Content:
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.
Displaying Students:
The code then displays the students in the database.
It retrieves all students using client.Students.ToList();.
Rendering to PDF:
The ChromePdfRenderer is instantiated.
IronPDF package requires a 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
Trial License is available from the IronPDF Licensing Page.
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.
9 .NET API products for your office documents