Skip to content

stormmuller/document-framework

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Document Framework

.NET Package .NET Tool

Nuget Package Nuget Tool

A light weight ORM for mongo and dotnet.

Notable features

  • EF style registration and usage
  • Migrations

Usage

  1. Add a model
public class Foo
{
  [BsonId]
  [BsonRepresentation(BsonType.ObjectId)]
  public string Id { get; set; }
  public string Text { get; set; }
}
  1. Create a MongoContext
dotnet df dbcontext scaffold -c BarMongoContext
  1. 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
  }
}
  1. Create a migration
dotnet df migrations add SeedFoos
  1. Implement the MigrationForward and MigrateBackward 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();
  }
}
  1. Register Context and mongo database in the ConfigureServices method in your Startup.cs
services
    .AddMongoContext<BarMongoContext>()
    .AddTransient<IMongoDatabase>()
  1. Sync migrations in the Configure method in your Startup.cs
app.ApplicationServices
        .GetRequiredService<BarMongoContext>()
        .SyncMigrations();
  1. 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();
    }
}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published