A light weight ORM for mongo and dotnet.
- EF style registration and usage
- Migrations
- Add a model
public class Foo
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Text { get; set; }
}
- Create a
MongoContext
dotnet df dbcontext scaffold -c BarMongoContext
- Add a collection for your model to you MongoContext
public class BarMongoContext : MongoContext
{
public readonly IMongoCollection<Foo> Foos;
public BarMongoContext(IMongoDatabase database, IEnumerable<IMongoMigration> migrations, ILogger<MongoContext> logger)
: base(migrations, database, logger)
{
Foos = GetOrAddCollection<Foo>("foos"); // Add this line in you generated mongo context
}
}
- Create a migration
dotnet df migrations add SeedFoos
- Implement the
MigrationForward
andMigrateBackward
methods in your new migration
public class SeedFoos : IMongoMigration
{
public string MigrationName => "20210420000000_SeedFoos";
private readonly IMongoDatabase _database;
public SeedFoos(IMongoDatabase database)
{
_database = database;
}
public void MigrateForward()
{
var fooCollection = _database.GetCollection<Foo>("foos");
fooCollection.InsertMany(new Foo[] {
new Foo { Text = "document-1" },
new Foo { Text = "document-2" }
});
}
public void MigrateBackward()
{
throw new NotImplementedException();
}
}
- Register Context and mongo database in the
ConfigureServices
method in yourStartup.cs
services
.AddMongoContext<BarMongoContext>()
.AddTransient<IMongoDatabase>()
- Sync migrations in the
Configure
method in yourStartup.cs
app.ApplicationServices
.GetRequiredService<BarMongoContext>()
.SyncMigrations();
- Use the Mongo context to query collections
public class SomeService
{
private readonly BarMongoContext _context;
public SomeService(BarMongoContext context)
{
_context = context;
}
public IEnumerable<Foo> GetSomeFooStuff(string text)
{
_context.Foos.Find(f => f.Text == text).ToEnumerable();
}
}