LiteDB .NET (How It Works For Developers)
LiteDB is a simple, fast, and lightweight embedded .NET document database. LiteDB .NET was inspired by the MongoDB database and its API is very similar to MongoDB’s official .NET API. LiteDB is a serverless database that works well for small projects and mobile applications.
This article will provide you with accurate instructions on utilizing the capabilities of LiteDB in your projects. We also introduce the use of IronPDF, a .NET library made by Iron Software, for generating and manipulating PDFs and how you can employ it to output a LiteDB database contents as a PDF for viewing and sharing.
Key Features of LiteDB
- Embedded Database: No need for a separate server. LiteDB runs within your application's process.
- Single Data File: You can store in a single file database, all of your data, simplifying deployment and backup.
- BSON Format: Uses BSON format for storage, ensuring fast read and write operations.
- LINQ Support: Fully supports LINQ for querying, making it intuitive for .NET developers.
- ACID Transactions: Ensures data integrity with support for ACID transactions.
- Cross-Platform: Works on Windows, Linux, and macOS.
Setting Up LiteDB in .NET Projects
Open your project in Visual Studio. Then, in the Solution Explorer, right-click on your project and choose "Manage NuGet Packages." Search for LiteDB and install it to incorporate this database solution into your project effortlessly.
Alternatively, you can install it by using Package Manager Console. To install LiteDB in the NuGet Package Manager Console, use the following command:
Install-Package LiteDB
Getting Started with LiteDB
Once installed, you can start using LiteDB in your application. Let's go through some examples to illustrate its usage.
Example 1: Creating and Inserting Data
First, let's create a simple Product
class to represent our data:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
Next, we'll create a database and insert some products:
using LiteDB;
using System;
class Program
{
static void Main()
{
// Open the database (or create it if it doesn't exist)
using (var db = new LiteDatabase(@"MyData.db"))
{
// Get a collection (or create, if it doesn't exist)
var products = db.GetCollection<Product>("products");
// Create a list of products to insert into the database
var productList = new[]
{
new Product { Id = 201, Name = "Apple", Price = 0.99m },
new Product { Id = 202, Name = "Banana", Price = 0.59m },
new Product { Id = 203, Name = "Orange", Price = 0.79m },
new Product { Id = 204, Name = "Grape", Price = 2.99m },
new Product { Id = 205, Name = "Watermelon", Price = 4.99m }
};
// Insert each product into the collection
foreach (var product in productList)
{
products.Insert(product);
}
Console.WriteLine("Product inserted successfully.");
}
}
}
using LiteDB;
using System;
class Program
{
static void Main()
{
// Open the database (or create it if it doesn't exist)
using (var db = new LiteDatabase(@"MyData.db"))
{
// Get a collection (or create, if it doesn't exist)
var products = db.GetCollection<Product>("products");
// Create a list of products to insert into the database
var productList = new[]
{
new Product { Id = 201, Name = "Apple", Price = 0.99m },
new Product { Id = 202, Name = "Banana", Price = 0.59m },
new Product { Id = 203, Name = "Orange", Price = 0.79m },
new Product { Id = 204, Name = "Grape", Price = 2.99m },
new Product { Id = 205, Name = "Watermelon", Price = 4.99m }
};
// Insert each product into the collection
foreach (var product in productList)
{
products.Insert(product);
}
Console.WriteLine("Product inserted successfully.");
}
}
}
Imports LiteDB
Imports System
Friend Class Program
Shared Sub Main()
' Open the database (or create it if it doesn't exist)
Using db = New LiteDatabase("MyData.db")
' Get a collection (or create, if it doesn't exist)
Dim products = db.GetCollection(Of Product)("products")
' Create a list of products to insert into the database
Dim productList = {
New Product With {
.Id = 201,
.Name = "Apple",
.Price = 0.99D
},
New Product With {
.Id = 202,
.Name = "Banana",
.Price = 0.59D
},
New Product With {
.Id = 203,
.Name = "Orange",
.Price = 0.79D
},
New Product With {
.Id = 204,
.Name = "Grape",
.Price = 2.99D
},
New Product With {
.Id = 205,
.Name = "Watermelon",
.Price = 4.99D
}
}
' Insert each product into the collection
For Each product In productList
products.Insert(product)
Next product
Console.WriteLine("Product inserted successfully.")
End Using
End Sub
End Class
Code Description
The code initializes a connection to a LiteDB database named "MyData.db" and retrieves a collection called "products." It then creates an array of Product
objects with various properties, such as ID, Name, and Price. Each product in the array is inserted into the "products" collection within the database. After successfully inserting all products, it prints a confirmation message to the console.
Output is as:
Example: Streamlining User Data Management
Imagine you're developing a mobile application that manages user accounts. Each user has a profile containing their name, email address, preferences (stored as a JSON object), and a list of favorite items. Here's how LiteDb.NET can simplify your data storage:
This code defines a User
class to represent user data and a UserManager
class to manage user operations in a LiteDb.NET database
using LiteDB;
using System.Collections.Generic;
public class User
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Dictionary<string, string> Preferences { get; set; }
public List<string> FavoriteItems { get; set; }
}
public class UserManager
{
private readonly LiteDatabase db;
public UserManager(string connectionString)
{
db = new LiteDatabase(connectionString);
}
public void SaveUser(User user)
{
var collection = db.GetCollection<User>("users");
collection.Insert(user);
}
public User GetUser(string userId)
{
var collection = db.GetCollection<User>("users");
return collection.FindById(userId);
}
public void UpdateUser(User user)
{
var collection = db.GetCollection<User>("users");
collection.Update(user);
}
public void DeleteUser(string userId)
{
var collection = db.GetCollection<User>("users");
collection.Delete(userId);
}
}
using LiteDB;
using System.Collections.Generic;
public class User
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Dictionary<string, string> Preferences { get; set; }
public List<string> FavoriteItems { get; set; }
}
public class UserManager
{
private readonly LiteDatabase db;
public UserManager(string connectionString)
{
db = new LiteDatabase(connectionString);
}
public void SaveUser(User user)
{
var collection = db.GetCollection<User>("users");
collection.Insert(user);
}
public User GetUser(string userId)
{
var collection = db.GetCollection<User>("users");
return collection.FindById(userId);
}
public void UpdateUser(User user)
{
var collection = db.GetCollection<User>("users");
collection.Update(user);
}
public void DeleteUser(string userId)
{
var collection = db.GetCollection<User>("users");
collection.Delete(userId);
}
}
Imports LiteDB
Imports System.Collections.Generic
Public Class User
<BsonId>
Public Property Id() As String
Public Property Name() As String
Public Property Email() As String
Public Property Preferences() As Dictionary(Of String, String)
Public Property FavoriteItems() As List(Of String)
End Class
Public Class UserManager
Private ReadOnly db As LiteDatabase
Public Sub New(ByVal connectionString As String)
db = New LiteDatabase(connectionString)
End Sub
Public Sub SaveUser(ByVal user As User)
Dim collection = db.GetCollection(Of User)("users")
collection.Insert(user)
End Sub
Public Function GetUser(ByVal userId As String) As User
Dim collection = db.GetCollection(Of User)("users")
Return collection.FindById(userId)
End Function
Public Sub UpdateUser(ByVal user As User)
Dim collection = db.GetCollection(Of User)("users")
collection.Update(user)
End Sub
Public Sub DeleteUser(ByVal userId As String)
Dim collection = db.GetCollection(Of User)("users")
collection.Delete(userId)
End Sub
End Class
This implementation effectively leverages LiteDb.NET's capabilities for user data management. The User
class stores user information, while the UserManager
class provides methods to save, retrieve, update, and delete users within the database.
LiteDB, embedded NoSQL database for .NET
LiteDB is perfect for small to medium-sized applications without user concurrency needs. For instance, it's great for a personal console app where you want to store data simply and swiftly. Developed solely in C#, it's lightweight, takes up less than 450KB, and doesn't rely on external dependencies.
Some more points, which are listed on their GitHub page:
- Serverless NoSQL Document Store
- Simple API, similar to MongoDB
- Thread-safe
- Written entirely in C#, LiteDB is compatible with .NET 4.5, NETStandard 1.3/2.0, packaged into a single DLL file that occupies less than 450KB.
- ACID with full transaction support
- Data recovery after write failure (WAL log file)
- Datafile encryption using AES cryptography
- You can easily map your Plain Old CLR Objects (POCO) classes to BsonDocument using either attributes or the fluent mapper API provided by LiteDB.
- Store files and stream data (like GridFS in MongoDB)
- Single data file storage (like SQLite)
- Index document fields for fast search
- LINQ support for queries
- SQL-Like commands to access/transform data
- LiteDB Studio – Nice UI for data access
- Open source and free for everyone – including commercial use
Introduction to IronPDF: A C# PDF Library
IronPDF, a premier C# PDF library, facilitates seamless creation, editing, and manipulation of PDFs in .NET projects. It offers a comprehensive API for tasks like HTML to PDF conversion, dynamic PDF generation, and data extraction. Utilizing a .NET Chromium engine ensures accurate rendering of HTML into PDF files, catering to diverse project needs across .NET Core, .NET Standard, and .NET Framework. IronPDF guarantees precision, simplicity, and efficiency in PDF generation from HTML content with support for web, desktop, and console applications.
Installing IronPDF Library
To initiate IronPDF in your project, install the library via the NuGet Package Manager within Visual Studio. Then simply follow these straightforward steps:
- Open Visual Studio and navigate to Solution Explorer.
- Right-click on Dependencies and select the "Manage NuGet Packages" option.
- Choose the "Browse" tab and search for "IronPdf."
- Select IronPDF and click "Install."
Alternatively, within Visual Studio, you can utilize the Package Manager Console to install the library by executing the following command:
Install-Package IronPdf
Example Usage of IronPDF with LiteDB
Here's a straightforward code example illustrating the usage of IronPDF to generate a PDF from HTML content, employing the 'using' statement to ensure proper resource disposal. Here we combine the functionality of LiteDB and IronPDF by showing how you can output the data within a LiteDB as a PDF for viewing purposes:
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPdf;
class Program
{
static void Main()
{
using (var db = new LiteDatabase(@"MyData.db"))
{
// Retrieve the 'products' collection or create it
var products = db.GetCollection<Product>("products");
// Add some initial products to the collection
var productList = new[]
{
new Product { Id = 101, Name = "Apple", Price = 0.99m },
new Product { Id = 102, Name = "Banana", Price = 0.59m },
new Product { Id = 103, Name = "Orange", Price = 0.79m },
new Product { Id = 104, Name = "Grape", Price = 2.99m },
new Product { Id = 105, Name = "Watermelon", Price = 4.99m }
};
// Insert products into the LiteDB collection
foreach (var product in productList)
{
products.Insert(product);
}
Console.WriteLine("Product inserted successfully.");
// Fetch all products from the database
var allProducts = GetAllProducts(db);
// Generate HTML content from the product list
string htmlContent = GenerateHtml(allProducts);
// Generate the PDF from the HTML content
GeneratePDF(htmlContent);
Console.WriteLine("PDF generated successfully.");
}
}
public static List<Product> GetAllProducts(LiteDatabase db)
{
var products = db.GetCollection<Product>("products");
return products.FindAll().ToList();
}
public static void GeneratePDF(string data)
{
// Set your IronPDF license key here
IronPdf.License.LicenseKey = "Your-License-Key";
Console.WriteLine("PDF Generating Started...");
// Create a PDF renderer
var renderer = new ChromePdfRenderer();
Console.WriteLine("PDF Processing ....");
// Render the HTML as a PDF
var pdf = renderer.RenderHtmlAsPdf(data);
// Save the PDF to a file
string filePath = "Data.pdf";
pdf.SaveAs(filePath);
Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
}
public static string GenerateHtml(List<Product> products)
{
// Build HTML table from product list
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>");
htmlBuilder.Append("<h1>Product List</h1>");
htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>");
// Add each product row to the HTML table
foreach (var product in products)
{
htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>");
}
htmlBuilder.Append("</table></body></html>");
return htmlBuilder.ToString();
}
}
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPdf;
class Program
{
static void Main()
{
using (var db = new LiteDatabase(@"MyData.db"))
{
// Retrieve the 'products' collection or create it
var products = db.GetCollection<Product>("products");
// Add some initial products to the collection
var productList = new[]
{
new Product { Id = 101, Name = "Apple", Price = 0.99m },
new Product { Id = 102, Name = "Banana", Price = 0.59m },
new Product { Id = 103, Name = "Orange", Price = 0.79m },
new Product { Id = 104, Name = "Grape", Price = 2.99m },
new Product { Id = 105, Name = "Watermelon", Price = 4.99m }
};
// Insert products into the LiteDB collection
foreach (var product in productList)
{
products.Insert(product);
}
Console.WriteLine("Product inserted successfully.");
// Fetch all products from the database
var allProducts = GetAllProducts(db);
// Generate HTML content from the product list
string htmlContent = GenerateHtml(allProducts);
// Generate the PDF from the HTML content
GeneratePDF(htmlContent);
Console.WriteLine("PDF generated successfully.");
}
}
public static List<Product> GetAllProducts(LiteDatabase db)
{
var products = db.GetCollection<Product>("products");
return products.FindAll().ToList();
}
public static void GeneratePDF(string data)
{
// Set your IronPDF license key here
IronPdf.License.LicenseKey = "Your-License-Key";
Console.WriteLine("PDF Generating Started...");
// Create a PDF renderer
var renderer = new ChromePdfRenderer();
Console.WriteLine("PDF Processing ....");
// Render the HTML as a PDF
var pdf = renderer.RenderHtmlAsPdf(data);
// Save the PDF to a file
string filePath = "Data.pdf";
pdf.SaveAs(filePath);
Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
}
public static string GenerateHtml(List<Product> products)
{
// Build HTML table from product list
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>");
htmlBuilder.Append("<h1>Product List</h1>");
htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>");
// Add each product row to the HTML table
foreach (var product in products)
{
htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>");
}
htmlBuilder.Append("</table></body></html>");
return htmlBuilder.ToString();
}
}
Imports LiteDB
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports IronPdf
Friend Class Program
Shared Sub Main()
Using db = New LiteDatabase("MyData.db")
' Retrieve the 'products' collection or create it
Dim products = db.GetCollection(Of Product)("products")
' Add some initial products to the collection
Dim productList = {
New Product With {
.Id = 101,
.Name = "Apple",
.Price = 0.99D
},
New Product With {
.Id = 102,
.Name = "Banana",
.Price = 0.59D
},
New Product With {
.Id = 103,
.Name = "Orange",
.Price = 0.79D
},
New Product With {
.Id = 104,
.Name = "Grape",
.Price = 2.99D
},
New Product With {
.Id = 105,
.Name = "Watermelon",
.Price = 4.99D
}
}
' Insert products into the LiteDB collection
For Each product In productList
products.Insert(product)
Next product
Console.WriteLine("Product inserted successfully.")
' Fetch all products from the database
Dim allProducts = GetAllProducts(db)
' Generate HTML content from the product list
Dim htmlContent As String = GenerateHtml(allProducts)
' Generate the PDF from the HTML content
GeneratePDF(htmlContent)
Console.WriteLine("PDF generated successfully.")
End Using
End Sub
Public Shared Function GetAllProducts(ByVal db As LiteDatabase) As List(Of Product)
Dim products = db.GetCollection(Of Product)("products")
Return products.FindAll().ToList()
End Function
Public Shared Sub GeneratePDF(ByVal data As String)
' Set your IronPDF license key here
IronPdf.License.LicenseKey = "Your-License-Key"
Console.WriteLine("PDF Generating Started...")
' Create a PDF renderer
Dim renderer = New ChromePdfRenderer()
Console.WriteLine("PDF Processing ....")
' Render the HTML as a PDF
Dim pdf = renderer.RenderHtmlAsPdf(data)
' Save the PDF to a file
Dim filePath As String = "Data.pdf"
pdf.SaveAs(filePath)
Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}")
End Sub
Public Shared Function GenerateHtml(ByVal products As List(Of Product)) As String
' Build HTML table from product list
Dim htmlBuilder As New StringBuilder()
htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>")
htmlBuilder.Append("<h1>Product List</h1>")
htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>")
' Add each product row to the HTML table
For Each product In products
htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>")
Next product
htmlBuilder.Append("</table></body></html>")
Return htmlBuilder.ToString()
End Function
End Class
The code connects to a LiteDB database, adds a list of products, retrieves all products, and generates an HTML representation of the product list. This HTML content is then used to create a PDF file using the IronPDF library. The process includes methods for adding products, fetching them, converting the product list to HTML, and generating the PDF.
Output
PDF File Output
Conclusion
LiteDB presents C# developers with a lightweight, serverless embedded document database solution, ideal for small projects and mobile applications, boasting features like MongoDB-inspired API, embedded databases, and cross-platform compatibility.
Simultaneously, IronPDF emerges as a premier C# PDF library, simplifying PDF generation and manipulation within .NET projects with its HTML to PDF conversion and NuGet integration. Both LiteDB and IronPDF offer valuable tools for developers, with LiteDB excelling in database management and IronPDF in PDF handling.
IronPDF provides a free trial to unlock its full potential in PDF generation and manipulation.
Frequently Asked Questions
What is LiteDB?
LiteDB is a simple, fast, and lightweight embedded .NET document database inspired by MongoDB. It is serverless and designed for small projects and mobile applications.
What are the key features of LiteDB?
Key features of LiteDB include being an embedded database, a single data file storage, BSON format for fast operations, support for LINQ queries, ACID transactions, and cross-platform compatibility.
How do I install LiteDB in a .NET project?
You can install LiteDB by opening your project in Visual Studio, managing NuGet Packages, and searching for LiteDB to install it. Alternatively, use the Package Manager Console with the command: Install-Package LiteDB.
How can I create and insert data using LiteDB?
You can create a class to represent your data, open a LiteDB database, get or create a collection, and insert data into the collection. The data is stored in the database file.
How can I generate a PDF from a LiteDB database?
You can use IronPDF, a C# PDF library, to generate and manipulate PDFs by outputting database contents as a PDF, facilitating data viewing and sharing.
How do I install a PDF library for .NET?
To install IronPDF, use the NuGet Package Manager within Visual Studio, search for IronPdf, and click 'Install.' Alternatively, use the Package Manager Console with the command: Install-Package IronPdf.
Can LiteDB handle ACID transactions?
Yes, LiteDB supports ACID transactions, ensuring data integrity and reliability.
What platforms does LiteDB support?
LiteDB is cross-platform and works on Windows, Linux, and macOS.
Is LiteDB suitable for large-scale applications?
LiteDB is ideal for small to medium-sized applications without high concurrency requirements. It is not recommended for large-scale applications with heavy concurrent access.
What formats can a C# PDF library convert into PDFs?
IronPDF can convert HTML content into PDFs, providing accurate rendering and manipulation within .NET projects.