### Complete Example: Basic Entity and Context Setup Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Demonstrates the setup of a basic entity, a DbContext, and performing a query, update, and save operation using MongoFramework. ```csharp using MongoFramework; using System.ComponentModel.DataAnnotations; public class MyEntity { public string Id { get; set; } public string Name { get; set; } public string Description { get; set; } } public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet MyEntities { get; set; } } ... var connection = MongoDbConnection.FromConnectionString("YOUR_CONNECTION_STRING"); using (var myContext = new MyContext(connection)) { var myEntity = myContext.MyEntities.Where(myEntity => myEntity.Name == "MongoFramework").FirstOrDefault(); myEntity.Description = "An 'Entity Framework'-like interface for MongoDB"; await myContext.SaveChangesAsync(); } ``` -------------------------------- ### Initialize MongoDbConnection Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Demonstrates creating a connection instance using either a URL or a connection string. ```csharp IMongoDbConnection connection; //FromUrl connection = MongoDbConnection.FromUrl(new MongoUrl("mongodb://localhost:27017/MyDatabase")); //MongoUrl comes from the official MongoDB driver //FromConnectionString connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MyDatabase"); ``` -------------------------------- ### Usage of Entity Buckets Source: https://context7.com/turnersoftware/mongoframework/llms.txt Illustrates how to add single or multiple readings to an entity bucket, query readings based on criteria, retrieve all unique sensor groups, and remove data for a specific sensor group. ```csharp // Usage using (var context = new IoTContext(connection)) { var sensorGroup = new SensorGroup { SensorId = "SENSOR-001", Date = DateTime.Today }; // Add single reading context.SensorReadings.Add(sensorGroup, new SensorReading { Timestamp = DateTime.UtcNow, Temperature = 22.5, Humidity = 45.0 }); // Add multiple readings at once var readings = Enumerable.Range(0, 50).Select(i => new SensorReading { Timestamp = DateTime.UtcNow.AddMinutes(-i), Temperature = 20.0 + (i * 0.1), Humidity = 40.0 + (i * 0.2) }); context.SensorReadings.AddRange(sensorGroup, readings); await context.SaveChangesAsync(); // Query readings for a specific sensor var todaysReadings = context.SensorReadings .WithGroup(sensorGroup) .Where(r => r.Temperature > 21.0) .ToList(); // Get all unique sensor groups var allGroups = context.SensorReadings.Groups().ToList(); // Remove all data for a sensor group context.SensorReadings.Remove(sensorGroup); await context.SaveChangesAsync(); } ``` -------------------------------- ### Configure Entity Mappings with Fluent API Source: https://context7.com/turnersoftware/mongoframework/llms.txt Use OnConfigureMapping to define collection names, keys, property element names, extra elements, and indexes. ```csharp using MongoFramework; using MongoFramework.Infrastructure.Mapping; public class Order { public string Id { get; set; } public string OrderNumber { get; set; } public decimal TotalAmount { get; set; } public DateTime OrderDate { get; set; } public Dictionary Metadata { get; set; } } public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet Orders { get; set; } protected override void OnConfigureMapping(MappingBuilder mappingBuilder) { mappingBuilder.Entity() .ToCollection("customer_orders") .HasKey(o => o.Id) .HasProperty(o => o.OrderNumber, b => b.HasElementName("order_num")) .HasProperty(o => o.TotalAmount, b => b.HasElementName("total")) .HasExtraElements(o => o.Metadata) // Store unknown fields in Metadata .HasIndex(o => o.OrderNumber, b => b.HasName("OrderNumberIdx").IsUnique()); } } // Usage using (var context = new MyContext(connection)) { var order = new Order { OrderNumber = "ORD-2024-001", TotalAmount = 299.99m, OrderDate = DateTime.UtcNow, Metadata = new Dictionary { { "source", "web" }, { "campaign", "summer-sale" } } }; context.Orders.Add(order); await context.SaveChangesAsync(); } ``` -------------------------------- ### Handle Extra Document Elements Source: https://context7.com/turnersoftware/mongoframework/llms.txt Demonstrates how to ignore or capture unmapped document fields using attributes or fluent configuration. ```csharp using MongoFramework; using MongoFramework.Attributes; // Option 1: Ignore extra elements [IgnoreExtraElements] public class FlexibleDocument { public string Id { get; set; } public string Name { get; set; } // Additional fields in the document are silently ignored } // Option 2: Capture extra elements in a dictionary public class ExtensibleDocument { public string Id { get; set; } public string Name { get; set; } [ExtraElements] public Dictionary AdditionalData { get; set; } } // Fluent configuration for extra elements public class DynamicContext : MongoDbContext { public DynamicContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet Documents { get; set; } protected override void OnConfigureMapping(MappingBuilder mappingBuilder) { mappingBuilder.Entity() .HasExtraElements(d => d.AdditionalData); } } // Usage using (var context = new DynamicContext(connection)) { var doc = new ExtensibleDocument { Name = "Flexible Record", AdditionalData = new Dictionary { { "customField1", "value1" }, { "customField2", 42 }, { "nestedData", new { foo = "bar", count = 5 } } } }; context.Documents.Add(doc); await context.SaveChangesAsync(); // Reading back preserves extra fields var loaded = context.Documents.Find(doc.Id); var customValue = loaded.AdditionalData["customField1"]; // "value1" } ``` -------------------------------- ### Perform Proximity Search with GeoNear Source: https://context7.com/turnersoftware/mongoframework/llms.txt Demonstrates how to add a location and then perform a proximity search using the SearchGeoNear extension method. Results are limited by maxDistance and ordered by proximity. ```csharp using (var context = new LocationContext(connection)) { // Add a location var restaurant = new Location { Name = "Downtown Cafe", Coordinates = new GeoJsonPoint( new GeoJson2DGeographicCoordinates(-73.9857, 40.7484)) // NYC coordinates }; context.Locations.Add(restaurant); await context.SaveChangesAsync(); // Search by proximity (geoNear) var searchPoint = new GeoJsonPoint( new GeoJson2DGeographicCoordinates(-73.9851, 40.7489)); var nearbyLocations = context.Locations .SearchGeoNear( l => l.Coordinates, searchPoint, distanceResultField: l => l.DistanceFromSearch, maxDistance: 5000) // 5km radius .Take(10) .ToList(); // Search within a polygon (geoIntersects) var searchArea = new GeoJsonPolygon( new GeoJsonPolygonCoordinates( new GeoJsonLinearRingCoordinates( new[] { new GeoJson2DGeographicCoordinates(-74.0, 40.7), new GeoJson2DGeographicCoordinates(-73.9, 40.7), new GeoJson2DGeographicCoordinates(-73.9, 40.8), new GeoJson2DGeographicCoordinates(-74.0, 40.8), new GeoJson2DGeographicCoordinates(-74.0, 40.7) }))) ); var locationsInArea = context.Locations .SearchGeoIntersecting(l => l.Coordinates, searchArea) .ToList(); } ``` -------------------------------- ### Create MongoDB Connection Source: https://context7.com/turnersoftware/mongoframework/llms.txt Establishes a connection to MongoDB using a connection string or MongoUrl with custom settings. The connection is managed by MongoDbConnection. ```csharp using MongoFramework; // Create connection from connection string var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MyDatabase"); // Create connection from MongoUrl with custom settings var mongoUrl = new MongoUrl("mongodb://localhost:27017/MyDatabase"); var connectionWithSettings = MongoDbConnection.FromUrl(mongoUrl, settings => { settings.MaxConnectionPoolSize = 100; settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5); }); // Use the connection with a context using (var context = new MyContext(connection)) { var entities = context.MyEntities.ToList(); } ``` -------------------------------- ### Perform CRUD Operations with MongoDbSet Source: https://context7.com/turnersoftware/mongoframework/llms.txt Demonstrates adding, finding, querying, updating, and deleting entities using MongoDbSet with automatic change tracking. ```csharp using MongoFramework; using MongoFramework.Linq; public class Article { public string Id { get; set; } public string Title { get; set; } public string Content { get; set; } public string Author { get; set; } public bool IsPublished { get; set; } } // Full CRUD example var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/Blog"); using (var context = new BlogContext(connection)) { // CREATE - Add single entity var article = new Article { Title = "Getting Started with MongoFramework", Content = "MongoFramework provides an EF-like experience...", Author = "Developer", IsPublished = false }; context.Articles.Add(article); // CREATE - Add multiple entities context.Articles.AddRange(new[] { new Article { Title = "Advanced Queries", Author = "Developer", IsPublished = true }, new Article { Title = "Performance Tips", Author = "Admin", IsPublished = true } }); await context.SaveChangesAsync(); // READ - Find by ID var foundArticle = context.Articles.Find(article.Id); var foundAsync = await context.Articles.FindAsync(article.Id); // READ - LINQ queries var publishedArticles = context.Articles .Where(a => a.IsPublished) .OrderBy(a => a.Title) .ToList(); // READ - Async queries var authorArticles = await context.Articles .Where(a => a.Author == "Developer") .ToListAsync(); // UPDATE - Modify tracked entity foundArticle.IsPublished = true; foundArticle.Title = "Updated Title"; await context.SaveChangesAsync(); // Only changed fields are written (diff-update) // UPDATE - Explicit update context.Articles.Update(foundArticle); await context.SaveChangesAsync(); // DELETE - Remove entity context.Articles.Remove(foundArticle); await context.SaveChangesAsync(); // DELETE - Remove by predicate (bulk delete) context.Articles.RemoveRange(a => a.Author == "Admin"); await context.SaveChangesAsync(); // DELETE - Remove by ID without loading entity context.Articles.RemoveById("some-article-id"); await context.SaveChangesAsync(); } ``` -------------------------------- ### Define Entity Buckets for Time-Series Data Source: https://context7.com/turnersoftware/mongoframework/llms.txt Sets up entity buckets for time-series data, defining the grouping key and sub-entity structure. The bucket options specify the size and the property used for time-based bucketing. ```csharp using MongoFramework; using MongoFramework.Attributes; // Define the grouping key public class SensorGroup { public string SensorId { get; set; } public DateTime Date { get; set; } } // Define the sub-entity stored in buckets public class SensorReading { public DateTime Timestamp { get; set; } // Required for bucketing public double Temperature { get; set; } public double Humidity { get; set; } } public class IoTContext : MongoDbContext { public IoTContext(IMongoDbConnection connection) : base(connection) { } [BucketSetOptions(bucketSize: 100, entityTimeProperty: nameof(SensorReading.Timestamp))] public MongoDbBucketSet SensorReadings { get; set; } } ``` -------------------------------- ### Perform Tenant-Specific Operations Source: https://context7.com/turnersoftware/mongoframework/llms.txt Instantiate the tenant context with a specific tenant ID to perform operations scoped to that tenant. Queries automatically filter by the context's tenant. ```csharp // Usage - each context instance is scoped to a specific tenant var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MultiTenantApp"); // Tenant A operations using (var tenantAContext = new MultiTenantContext(connection, "tenant-a")) { var doc = new TenantDocument { TenantId = "tenant-a", // Must match context tenant Name = "Tenant A Document", Content = "Private content for Tenant A" }; tenantAContext.Documents.Add(doc); await tenantAContext.SaveChangesAsync(); // Queries automatically filter by tenant var tenantADocs = tenantAContext.Documents.ToList(); // Only tenant-a docs } // Tenant B operations using (var tenantBContext = new MultiTenantContext(connection, "tenant-b")) { var doc = new TenantDocument { TenantId = "tenant-b", Name = "Tenant B Document", Content = "Private content for Tenant B" }; tenantBContext.Documents.Add(doc); await tenantBContext.SaveChangesAsync(); // Cannot access tenant-a documents var tenantBDocs = tenantBContext.Documents.ToList(); // Only tenant-b docs } ``` -------------------------------- ### Integrate MiniProfiler with MongoFramework Source: https://context7.com/turnersoftware/mongoframework/llms.txt Configures a MongoDB connection with a MiniProfiler diagnostic listener to track database operation performance. ```csharp using MongoFramework; using MongoFramework.Profiling.MiniProfiler; using StackExchange.Profiling; // Configure MiniProfiler in your application startup // For ASP.NET Core: // services.AddMiniProfiler(options => options.RouteBasePath = "/profiler"); // Create connection with MiniProfiler diagnostic listener var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MyApp"); connection.DiagnosticListener = new MiniProfilerDiagnosticListener(); using (var context = new MyContext(connection)) { // Start profiling using (MiniProfiler.Current.Step("Database Operations")) { // All MongoDB operations are now profiled var users = context.Users.Where(u => u.IsActive).ToList(); var newUser = new User { Name = "Test User", IsActive = true }; context.Users.Add(newUser); await context.SaveChangesAsync(); } // View profiling results var profiler = MiniProfiler.Current; Console.WriteLine($"Total duration: {profiler.DurationMilliseconds}ms"); foreach (var timing in profiler.GetTimingHierarchy()) { Console.WriteLine($"{timing.Name}: {timing.DurationMilliseconds}ms"); } } ``` -------------------------------- ### Configure Index via Fluent Mapping Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Applies an index to a specific property using the fluent mapping builder. ```csharp mappingBuilder.Entity() .HasIndex(e => e.EmailAddress, b => b.HasName("Email").IsDescending(false)); ``` -------------------------------- ### Configure Index via Attribute Mapping Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Applies an index to a property using the IndexAttribute. ```csharp public class IndexExample { public string Id { get; set; } [Index("Email", IndexSortOrder.Ascending)] public string EmailAddress { get; set; } public string Name { get; set; } } ``` -------------------------------- ### Define Entity Bucket Models and Context Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Define the grouping and item models for your bucket, along with the DbContext, specifying bucket options like size and the time property. ```csharp public class MyBucketGrouping { public string SensorId { get; set; } public DateTime Date { get; set; } } public class MyBucketItem { public DateTime EntryTime { get; set; } public int Value { get; set; } } public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } [BucketSetOptions(bucketSize: 1000, entityTimeProperty: nameof(MyBucketItem.EntryTime))] public MongoDbBucketSet MyBuckets { get; set; } } ``` -------------------------------- ### Configure MongoDB Indexes with Attributes and Fluent Mapping Source: https://context7.com/turnersoftware/mongoframework/llms.txt Define indexes using the [Index] attribute on model properties or via the HasIndex method within a MongoDbContext's OnConfigureMapping override. ```csharp using MongoFramework; using MongoFramework.Attributes; // Attribute-based indexing public class SearchableProduct { public string Id { get; set; } [Index("SKU_Index", IndexSortOrder.Ascending)] public string SKU { get; set; } [Index(IndexType.Text)] // Text index for full-text search public string Description { get; set; } // Compound index - same name groups properties together [Index("Category_Price", IndexSortOrder.Ascending, IndexPriority = 1)] public string Category { get; set; } [Index("Category_Price", IndexSortOrder.Descending, IndexPriority = 2)] public decimal Price { get; set; } [Index(IndexSortOrder.Ascending, IsUnique = true)] public string Barcode { get; set; } } // Fluent indexing with compound indexes public class GeoLocation { public double Latitude { get; set; } public double Longitude { get; set; } } public class Store { public string Id { get; set; } public string Name { get; set; } public string Region { get; set; } public int EmployeeCount { get; set; } public GeoLocation Location { get; set; } } public class StoreContext : MongoDbContext { public StoreContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet Stores { get; set; } protected override void OnConfigureMapping(MappingBuilder mappingBuilder) { mappingBuilder.Entity() // Single field index .HasIndex(s => s.Name, b => b.HasName("NameIdx").IsUnique()) // Compound index on multiple fields .HasIndex(s => new { s.Region, s.EmployeeCount }, b => { b.HasName("RegionEmployeeIdx") .IsDescending(false, true); // Region ASC, EmployeeCount DESC }); } } ``` -------------------------------- ### Implement Multi-Tenant Entity and Context Source: https://context7.com/turnersoftware/mongoframework/llms.txt Define entities implementing IHaveTenantId and a custom MongoDbTenantContext. Ensure the TenantId property is correctly set for data isolation. ```csharp using MongoFramework; // Entity must implement IHaveTenantId for tenant filtering public class TenantDocument : IHaveTenantId { public string Id { get; set; } public string TenantId { get; set; } // Required by IHaveTenantId public string Name { get; set; } public string Content { get; set; } } public class MultiTenantContext : MongoDbTenantContext { public MultiTenantContext(IMongoDbConnection connection, string tenantId) : base(connection, tenantId) { } public MongoDbSet Documents { get; set; } } ``` -------------------------------- ### Execute Special Queries Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Performs text and geospatial queries which return an IQueryable for further LINQ operations. ```csharp myContext.MyDbSet.SearchText("text to search"); myContext.MyDbSet.SearchGeoIntersecting(e => e.FieldWithCoordinates, yourGeoJsonPolygon); myContext.MyDbSet.SearchGeoNear(e => e.FieldWithCoordinates, yourGeoJsonPoint); ``` -------------------------------- ### Handle Cross-Tenant Access Validation Source: https://context7.com/turnersoftware/mongoframework/llms.txt The framework automatically throws a MultiTenantException if an attempt is made to add or modify data with a TenantId that does not match the context's tenant. ```csharp // Validation prevents cross-tenant data access using (var context = new MultiTenantContext(connection, "tenant-a")) { try { var wrongTenantDoc = new TenantDocument { TenantId = "tenant-b", // Wrong tenant! Name = "Invalid" }; context.Documents.Add(wrongTenantDoc); await context.SaveChangesAsync(); // Throws MultiTenantException } catch (MultiTenantException ex) { Console.WriteLine($"Tenant validation failed: {ex.Message}"); } } ``` -------------------------------- ### Configure Compound Index via Fluent Mapping Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Defines a compound index across multiple properties, including nested structures. ```csharp public class TestModelBase { public string Id { get; set; } public string Name { get; set; } public IEnumerable ManyOfThem { get; set; } } public class TestModel : TestModelBase { public Dictionary ExtraElements { get; set; } public string OtherName { get; set; } public int SomethingIndexable { get; set; } public NestedModelBase OneOfThem { get; set; } } public class NestedModelBase { public string Description { get; set; } } mappingBuilder.Entity() .HasIndex(m => new { m.SomethingIndexable, m.OneOfThem.Description, m.ManyOfThem.First().AnotherThingIndexable }, b => { b.HasName("MyIndex") .IsDescending(true, false, false) }); ``` -------------------------------- ### Configure Entity Mapping with Attributes Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Use data annotation attributes to define collection and property mappings directly on the entity class. ```csharp using MongoFramework; using System.ComponentModel.DataAnnotations; [Table("MyCustomEntities")] public class MyEntity { public string Id { get; set; } [Column("MappedName")] public string Name { get; set; } public string Description { get; set; } } public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet MyEntities { get; set; } } ``` -------------------------------- ### Execute Asynchronous LINQ Operations Source: https://context7.com/turnersoftware/mongoframework/llms.txt Perform non-blocking database queries using async extension methods like ToListAsync, FirstOrDefaultAsync, and AsAsyncEnumerable. ```csharp using MongoFramework; using MongoFramework.Linq; public class Invoice { public string Id { get; set; } public string CustomerId { get; set; } public decimal Amount { get; set; } public DateTime InvoiceDate { get; set; } public bool IsPaid { get; set; } } using (var context = new BillingContext(connection)) { // Async collection operations var allInvoices = await context.Invoices.ToListAsync(); var invoiceArray = await context.Invoices.ToArrayAsync(); // Async single-result operations var firstInvoice = await context.Invoices.FirstAsync(); var firstOrNull = await context.Invoices.FirstOrDefaultAsync(); var singleInvoice = await context.Invoices .Where(i => i.Id == "INV-001") .SingleOrDefaultAsync(); // Async with predicates var unpaidInvoice = await context.Invoices .FirstOrDefaultAsync(i => !i.IsPaid); // Async aggregations var totalCount = await context.Invoices.CountAsync(); var unpaidCount = await context.Invoices.CountAsync(i => !i.IsPaid); var hasUnpaid = await context.Invoices.AnyAsync(i => !i.IsPaid); // Async min/max var maxAmount = await context.Invoices.MaxAsync(i => i.Amount); var minDate = await context.Invoices.MinAsync(i => i.InvoiceDate); // Async sum var totalAmount = await context.Invoices .Where(i => i.IsPaid) .SumAsync(i => i.Amount); // Async enumerable for streaming large datasets await foreach (var invoice in context.Invoices .Where(i => i.Amount > 1000) .AsAsyncEnumerable()) { Console.WriteLine($"High-value invoice: {invoice.Id}"); } } ``` -------------------------------- ### Configure Entity Mapping with Fluent API Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Use the fluent mapping builder within a MongoDbContext to define custom collection names and property mappings. ```csharp using MongoFramework; public class MyEntity { public string Id { get; set; } public string Name { get; set; } public string Description { get; set; } } public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet MyEntities { get; set; } protected override void OnConfigureMapping(MappingBuilder mappingBuilder) { mappingBuilder.Entity() .HasProperty(m => m.Name, b => b.HasElementName("MappedName")) .ToCollection("MyCustomEntities"); } } ``` -------------------------------- ### Enable Runtime Type Discovery for Polymorphic Types Source: https://context7.com/turnersoftware/mongoframework/llms.txt Use the [RuntimeTypeDiscovery] attribute on an abstract base class to enable automatic discovery of derived types for serialization and deserialization. This allows storing different derived types in the same collection. ```csharp using MongoFramework; using MongoFramework.Attributes; [RuntimeTypeDiscovery] // Enable automatic type discovery public abstract class Notification { public string Id { get; set; } public string UserId { get; set; } public DateTime CreatedAt { get; set; } public bool IsRead { get; set; } } // Derived types are automatically discovered at runtime public class EmailNotification : Notification { public string Subject { get; set; } public string Body { get; set; } } public class PushNotification : Notification { public string Title { get; set; } public string Message { get; set; } public string DeviceToken { get; set; } } public class SmsNotification : Notification { public string PhoneNumber { get; set; } public string Text { get; set; } } public class NotificationContext : MongoDbContext { public NotificationContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet Notifications { get; set; } } ``` ```csharp // Usage - polymorphic entities work automatically using (var context = new NotificationContext(connection)) { // Add different notification types to the same collection context.Notifications.Add(new EmailNotification { UserId = "user-1", CreatedAt = DateTime.UtcNow, Subject = "Welcome!", Body = "Thank you for signing up." }); context.Notifications.Add(new PushNotification { UserId = "user-1", CreatedAt = DateTime.UtcNow, Title = "New Message", Message = "You have a new message", DeviceToken = "abc123" }); context.Notifications.Add(new SmsNotification { UserId = "user-2", CreatedAt = DateTime.UtcNow, PhoneNumber = "+1234567890", Text = "Your verification code is 123456" }); await context.SaveChangesAsync(); // Query returns correctly typed objects var allNotifications = context.Notifications.ToList(); foreach (var notification in allNotifications) { switch (notification) { case EmailNotification email: Console.WriteLine($"Email: {email.Subject}"); break; case PushNotification push: Console.WriteLine($"Push: {push.Title}"); break; case SmsNotification sms: Console.WriteLine($"SMS to: {sms.PhoneNumber}"); break; } } } ``` -------------------------------- ### Add Data to Entity Buckets Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Use the AddRange method to add multiple grouping entities and their associated items to a bucket. Ensure to call SaveChangesAsync to persist the changes. ```csharp using (var context = new MyContext(MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MyDatabase"))) { context.MyBuckets.AddRange(new MyBucketGrouping { SensorId = "ABC123", Date = DateTime.Parse("2020-04-04") }, new [] { new MyBucketItem { EntryTime = DateTime.Parse("2020-04-04T01:00"), Amount = 123 }, new MyBucketItem { EntryTime = DateTime.Parse("2020-04-04T02:00"), Amount = 456 }, new MyBucketItem { EntryTime = DateTime.Parse("2020-04-04T03:00"), Amount = 789 } }); await context.SaveChangesAsync(); } ``` -------------------------------- ### Configure Runtime Type Discovery for Base Models Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Apply the RuntimeTypeDiscovery attribute to a base class to enable automatic discovery of derived types during deserialization. This avoids the need for BsonKnownTypes. ```csharp [RuntimeTypeDiscovery] public class KnownBaseModel { } public class UnknownChildModel : KnownBaseModel { } public class UnknownGrandChildModel : UnknownChildModel { } ``` -------------------------------- ### Entity Mapping with Attributes Source: https://context7.com/turnersoftware/mongoframework/llms.txt Customizes collection names, property mappings, and keys using standard .NET data annotations. Properties marked with [NotMapped] are excluded from database operations. ```csharp using MongoFramework; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; [Table("customers", Schema = "sales")] // Maps to "sales.customers" collection public class Customer { [Key] // Explicit key definition (optional for properties named "Id") public string CustomerId { get; set; } [Column("full_name")] // Maps to "full_name" field in MongoDB public string Name { get; set; } [NotMapped] // Excluded from database operations public string TemporaryData { get; set; } public string Email { get; set; } public List
Addresses { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string PostalCode { get; set; } } // Usage using (var context = new MyContext(connection)) { var customer = new Customer { CustomerId = "CUST-001", Name = "Jane Smith", Email = "jane@example.com", TemporaryData = "This won't be saved", Addresses = new List
{ new Address { Street = "123 Main St", City = "New York", PostalCode = "10001" } } }; context.Customers.Add(customer); await context.SaveChangesAsync(); } ``` -------------------------------- ### Define Location Model with Geo Index Source: https://context7.com/turnersoftware/mongoframework/llms.txt Defines a C# model for location data, including a GeoJSON point for coordinates and an index for geospatial queries. The DistanceFromSearch property is populated by geoNear queries. ```csharp using MongoFramework; using MongoFramework.Attributes; using MongoFramework.Linq; using MongoDB.Driver.GeoJsonObjectModel; public class Location { public string Id { get; set; } public string Name { get; set; } [Index(IndexType.Geo2dSphere)] public GeoJsonPoint Coordinates { get; set; } public double DistanceFromSearch { get; set; } // Populated by geoNear queries } ``` -------------------------------- ### Define MongoDbContext Source: https://github.com/turnersoftware/mongoframework/blob/main/README.md Creates a custom context class inheriting from MongoDbContext to manage entity sets. ```csharp public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet MyEntities { get; set; } public MongoDbSet MyOtherEntities { get; set; } } ``` -------------------------------- ### Define MongoDbContext Source: https://context7.com/turnersoftware/mongoframework/llms.txt Defines a context by inheriting from MongoDbContext and declaring MongoDbSet properties for collections. This is the central point for interacting with MongoDB. ```csharp using MongoFramework; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public class User { public string Id { get; set; } public string Name { get; set; } public string Email { get; set; } public DateTime CreatedAt { get; set; } } public class Product { public string Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class MyContext : MongoDbContext { public MyContext(IMongoDbConnection connection) : base(connection) { } public MongoDbSet Users { get; set; } public MongoDbSet Products { get; set; } } // Usage var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MyApp"); using (var context = new MyContext(connection)) { // Add a new user var user = new User { Name = "John Doe", Email = "john@example.com", CreatedAt = DateTime.UtcNow }; context.Users.Add(user); await context.SaveChangesAsync(); // Query users var activeUsers = context.Users.Where(u => u.CreatedAt > DateTime.UtcNow.AddDays(-30)).ToList(); } ``` -------------------------------- ### Perform Full-Text Search Source: https://context7.com/turnersoftware/mongoframework/llms.txt Use the SearchText method on collections with defined text indexes to perform full-text queries, optionally combined with standard LINQ filters. ```csharp using MongoFramework; using MongoFramework.Attributes; using MongoFramework.Linq; public class BlogPost { public string Id { get; set; } [Index(IndexType.Text)] public string Title { get; set; } [Index(IndexType.Text)] public string Body { get; set; } public string[] Tags { get; set; } public DateTime PublishedAt { get; set; } } using (var context = new BlogContext(connection)) { // Simple text search var results = context.BlogPosts .SearchText("mongodb tutorial") .ToList(); // Text search with additional filters var recentResults = context.BlogPosts .SearchText("performance optimization") .Where(p => p.PublishedAt > DateTime.UtcNow.AddMonths(-6)) .OrderByDescending(p => p.PublishedAt) .Take(10) .ToList(); // Async text search var asyncResults = await context.BlogPosts .SearchText("async programming") .ToListAsync(); } ``` -------------------------------- ### Automatic Change Tracking and Diff-Updates Source: https://context7.com/turnersoftware/mongoframework/llms.txt MongoFramework automatically tracks entity changes. Only modified fields are written to the database during SaveChangesAsync, optimizing update operations. The ChangeTracker provides access to entity states and values. ```csharp using MongoFramework; using MongoFramework.Infrastructure; public class Profile { public string Id { get; set; } public string Username { get; set; } public string Bio { get; set; } public int FollowerCount { get; set; } public DateTime LastUpdated { get; set; } } // Usage example using (var context = new ProfileContext(connection)) { // Create and save an entity var profile = new Profile { Username = "johndoe", Bio = "Software developer", FollowerCount = 100, LastUpdated = DateTime.UtcNow }; context.Profiles.Add(profile); await context.SaveChangesAsync(); // Modify the entity - only changed fields will be written profile.FollowerCount = 150; profile.LastUpdated = DateTime.UtcNow; // Bio and Username won't be included in the update await context.SaveChangesAsync(); // Access change tracker directly var entries = context.ChangeTracker.Entries(); foreach (var entry in entries) { Console.WriteLine($"Entity: {entry.EntityType.Name}, State: {entry.State}"); if (entry.State == EntityEntryState.Updated) { Console.WriteLine($"Original: {entry.OriginalValues}"); Console.WriteLine($"Current: {entry.CurrentValues}"); } } // Attach an existing entity for tracking var existingProfile = new Profile { Id = "known-id", Username = "existing" }; context.Attach(existingProfile); // Marks as unchanged existingProfile.Bio = "Updated bio"; await context.SaveChangesAsync(); // Detects and saves the change // Disable tracking for read-only queries (better performance) var readOnlyProfiles = context.Profiles .AsNoTracking() .Where(p => p.FollowerCount > 50) .ToList(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.