Mongo Context provides a familiar experience for developers that have worked with Entity Framework.
- Mongo.Context is a C# library that provides an Entity Framework-like experience for MongoDB, enabling familiar patterns for .NET developers.
- The architecture centers around
MongoContext, which acts as the main entry point for database operations, similar toDbContextin EF. - Collections are accessed via generic
MongoSet<TEntity>properties, supporting LINQ queries and expression-based access. - Class mapping and index configuration are handled via
MongoClassMapandMongoBuilder.
MongoContext: Main context class. Handles connection, database selection, and registration of entity mappings and indexes.MongoSet<TEntity>: Wrapper for MongoDB collections, supports LINQ and direct queries.MongoBuilder/IMongoBuilder: Used for registering class maps and initializing sets/indexes.MongoClassMap: Used to configure collection names, property mappings, and indexes for entities.- Example context: See
Mongo.Context.Example/Context.csfor custom context and mapping patterns.
- Build: Standard .NET build (
dotnet build Mongo.Context.sln). - Test: No explicit test project found; add tests in
Mongo.Context.AppHost/_Tests.csor similar. - Debug: Use standard .NET debugging tools. Entry point for examples is likely in
Mongo.Context.Example/Context.cs.
- Entity Registration: Override
OnRegisterClassesin your context to register class maps and indexes. UsemongoBuilder.FromAssemblyto auto-register maps from an assembly. - Manual Mapping: Use
mongoBuilder.Entry<TEntity>()to manually configure collection names, property mappings, and indexes. - Indexing: Add indexes via
MongoClassMap.AddIndexor set theIndexesproperty. - Pluralization: Collection names are pluralized using internal helpers (see
Internal/NamePluralization.cs). - Extensions: Utility methods for collections are in
Extensions/IEnumerableExtensions.cs.
- MongoDB Driver: Uses
MongoDB.Driverand related packages for database operations. - Mapping: Custom class maps (e.g.,
CustomerMap) should inherit fromMongoClassMap<TEntity>and configure ID serialization/generation as needed.
public class Context : MongoContext {
public MongoSet<Customer> Customers { get; set; }
protected override void OnRegisterClasses(MongoBuilder mongoBuilder) {
mongoBuilder.FromAssembly(typeof(Context).Assembly);
mongoBuilder.Entry<Customer>().SetCollectionName("SuperCustomers");
mongoBuilder.Entry<Customer>().AddIndex(new MongoIndex { Keys = new[] { "Name" } });
}
}