Okay, here's a C# example demonstrating how to save a Person class to LiteDB.
First, you'll need to install the LiteDB NuGet package:
Install-Package LiteDB
1. Define the Person Class:
using LiteDB; // For BsonId attribute
public class Person
{
// LiteDB will use this as the primary key.
// If 'true' is passed to BsonId, it will auto-increment for int types.
// If you use ObjectId, LiteDB handles its generation automatically.
[BsonId(true)] // Auto-increment for int PK
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int Age { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string>? Hobbies { get; set; } // Example of a collection
public override string ToString()
{
return $"Id: {Id}, Name: {FirstName} {LastName}, Age: {Age}, DOB: {DateOfBirth.ToShortDateString()}, Hobbies: {(Hobbies != null ? string.Join(", ", Hobbies) : "None")}";
}
}
[BsonId(true)]: This attribute marks the Id property as the primary key.
- If the type is
int (or long) and true is passed, LiteDB will treat it as an auto-incrementing ID.
- If you prefer
ObjectId (LiteDB's native BSON ObjectId), you'd define it as public ObjectId Id { get; set; } and can omit (true) or just use [BsonId]. LiteDB will generate it.
- Nullable reference types (
string?, List<string>?) are used for good practice in modern C#.
2. Create a Service/Repository Class with the Save Method:
using LiteDB;
using System;
using System.IO; // For Path combining
using System.Collections.Generic; // For List
public class PersonService
{
private readonly string _dbPath;
private const string CollectionName = "people"; // Name of the collection in LiteDB
// Constructor to specify the database path
public PersonService(string databasePath)
{
_dbPath = databasePath;
// Ensure the directory exists (optional, LiteDB creates the file if not present)
var dbDirectory = Path.GetDirectoryName(_dbPath);
if (!string.IsNullOrEmpty(dbDirectory) && !Directory.Exists(dbDirectory))
{
Directory.CreateDirectory(dbDirectory);
}
}
/// <summary>
/// Saves (Inserts or Updates) a Person object to the LiteDB database.
/// </summary>
/// <param name="person">The Person object to save.</param>
/// <returns>The ID of the saved person. If it was an insert of an int with auto-increment,
/// this will be the newly generated ID.</returns>
public int SavePerson(Person person)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
// 'using' ensures the database connection is properly disposed
using (var db = new LiteDatabase(_dbPath))
{
// Get a collection (or create it if it doesn't exist)
var col = db.GetCollection<Person>(CollectionName);
// Upsert will insert a new document if it does not exist,
// or update an existing document if the _id (Person.Id) matches.
// For int IDs with [BsonId(true)], if person.Id is 0, it's an insert,
// otherwise it's an update.
col.Upsert(person);
// Optional: Ensure an index on properties you frequently query
// This is usually done once, perhaps at application startup or in the constructor
// col.EnsureIndex(x => x.LastName);
// col.EnsureIndex(x => x.DateOfBirth);
return person.Id; // The Id will be populated if it was an insert with auto-ID
}
}
/// <summary>
/// Retrieves a person by their ID.
/// </summary>
/// <param name="id">The ID of the person to retrieve.</param>
/// <returns>The Person object if found, otherwise null.</returns>
public Person? GetPersonById(int id)
{
using (var db = new LiteDatabase(_dbPath))
{
var col = db.GetCollection<Person>(CollectionName);
return col.FindById(id);
}
}
/// <summary>
/// Retrieves all people from the database.
/// </summary>
/// <returns>A list of all Person objects.</returns>
public List<Person> GetAllPeople()
{
using (var db = new LiteDatabase(_dbPath))
{
var col = db.GetCollection<Person>(CollectionName);
return col.FindAll().ToList();
}
}
/// <summary>
/// Deletes a person by their ID.
/// </summary>
/// <param name="id">The ID of the person to delete.</param>
/// <returns>True if a document was deleted, false otherwise.</returns>
public bool DeletePerson(int id)
{
using(var db = new LiteDatabase(_dbPath))
{
var col = db.GetCollection<Person>(CollectionName);
return col.Delete(id);
}
}
}
3. Example Usage (e.g., in Program.cs for a console app):
using System;
using System.IO; // For Path
using System.Linq; // For LINQ methods like Any()
public class Program
{
public static void Main(string[] args)
{
// Define the path for the LiteDB database file
// string dbPath = "MyData.db"; // In the same directory as the executable
string dbPath = Path.Combine(AppContext.BaseDirectory, "MyData.db");
Console.WriteLine($"Database will be at: {dbPath}");
// Delete existing DB for a clean run (optional)
if (File.Exists(dbPath))
{
File.Delete(dbPath);
Console.WriteLine("Old database deleted for fresh start.");
}
var personService = new PersonService(dbPath);
// --- Create and Save a new Person ---
Console.WriteLine("\n--- Creating and Saving New Person ---");
var newPerson = new Person
{
// Id will be auto-generated because it's 0 and [BsonId(true)]
FirstName = "John",
LastName = "Doe",
Age = 30,
DateOfBirth = new DateTime(1993, 5, 15),
Hobbies = new List<string> { "Reading", "Coding" }
};
int newPersonId = personService.SavePerson(newPerson);
Console.WriteLine($"Saved new person with ID: {newPersonId}"); // newPerson.Id is now populated
Console.WriteLine(newPerson.ToString());
// --- Retrieve and Update an existing Person ---
Console.WriteLine("\n--- Retrieving and Updating Person ---");
Person? retrievedPerson = personService.GetPersonById(newPersonId);
if (retrievedPerson != null)
{
Console.WriteLine($"Retrieved: {retrievedPerson}");
retrievedPerson.Age = 31;
retrievedPerson.Hobbies?.Add("Hiking");
personService.SavePerson(retrievedPerson); // This will be an update
Console.WriteLine($"Updated: {personService.GetPersonById(newPersonId)}");
}
else
{
Console.WriteLine($"Person with ID {newPersonId} not found for update.");
}
// --- Create another person ---
Console.WriteLine("\n--- Creating Another Person ---");
var anotherPerson = new Person
{
FirstName = "Jane",
LastName = "Smith",
Age = 28,
DateOfBirth = new DateTime(1995, 10, 20)
// Hobbies can be null
};
int anotherPersonId = personService.SavePerson(anotherPerson);
Console.WriteLine($"Saved another person with ID: {anotherPersonId}");
Console.WriteLine(anotherPerson.ToString());
// --- List all people ---
Console.WriteLine("\n--- Listing All People ---");
var allPeople = personService.GetAllPeople();
if (allPeople.Any())
{
foreach (var p in allPeople)
{
Console.WriteLine(p.ToString());
}
}
else
{
Console.WriteLine("No people found in the database.");
}
// --- Delete a person ---
Console.WriteLine("\n--- Deleting a Person ---");
if (retrievedPerson != null) // use the ID from the first person
{
bool deleted = personService.DeletePerson(retrievedPerson.Id);
Console.WriteLine(deleted ? $"Person with ID {retrievedPerson.Id} deleted." : $"Failed to delete person with ID {retrievedPerson.Id}.");
}
Console.WriteLine("\n--- Listing All People After Deletion ---");
allPeople = personService.GetAllPeople();
if (allPeople.Any())
{
foreach (var p in allPeople)
{
Console.WriteLine(p.ToString());
}
}
else
{
Console.WriteLine("No people found in the database.");
}
Console.WriteLine("\nDone. Check the MyData.db file.");
}
}
Explanation:
PersonService:
- Takes the database path in its constructor.
CollectionName: Defines the name of the "table" (collection) in LiteDB where Person objects will be stored.
SavePerson(Person person) Method:
using (var db = new LiteDatabase(_dbPath)): This opens a connection to the LiteDB file. The using statement ensures that the database connection is properly closed and disposed of, even if errors occur.
var col = db.GetCollection<Person>(CollectionName): This gets a reference to the collection. If the collection doesn't exist, LiteDB creates it automatically. The generic type <Person> tells LiteDB how to map the documents in the collection to your C# class.
col.Upsert(person): This is the core command.
- Upsert = Update or Insert.
- If a document with the same
_id (which maps to Person.Id because of [BsonId]) already exists in the collection, LiteDB will update it.
- If no document with that
_id exists (or if Person.Id is 0 for an auto-incrementing int ID), LiteDB will insert a new document. If Person.Id was 0 and [BsonId(true)] is used, LiteDB will assign a new auto-incremented ID to person.Id.
return person.Id;: After an upsert, especially an insert with an auto-generated ID, the person.Id property will be populated with the ID assigned by LiteDB.
- Indexes (
col.EnsureIndex(...)):
- Although not strictly part of saving, if you plan to query your data frequently based on specific fields (e.g.,
LastName), creating an index on that field will significantly improve query performance. You typically call EnsureIndex once (e.g., on application startup or when the PersonService is first initialized).
ObjectId Alternative for ID:
If you prefer LiteDB's ObjectId for globally unique IDs:
public class PersonWithObjectId
{
[BsonId] // No need for (true) with ObjectId
public ObjectId Id { get; set; } // LiteDB generates this if it's null or ObjectId.Empty
public string? FirstName { get; set; }
// ... other properties
}
In this case, would be an type, and would likely return . The logic remains the same. LiteDB automatically generates an for new documents if is or .
This comprehensive example provides a robust way to save Person objects to a LiteDB database.