Search code examples
mongodbasp.net-coremongodb-.net-driver

.Net Core + MongoDb Create Database Automatically according to entities


I have been working on a .Net Core project and I want to use MongoDb as a database implementation. I have created my entities that will be created as Collections. You can see the entities below.

When I start the project and if the database does not exist on the server, database and collections must be created according to entities that I have created. I should not create a database manually.

For Mssql, I am using FluentMigrator for this process. How can I handle it for MongoDb?

/// <summary>
/// BaseEntity abstract class implementations
/// </summary>
public abstract class BaseEntity : IEntity<string>
{
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonId]
    [BsonElement(Order = 0)]
    public string Id { get; } = ObjectId.GenerateNewId().ToString();

    [BsonRepresentation(BsonType.DateTime)]
    [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
    [BsonElement(Order = 101)]
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}


public class Basket : BaseEntity
{
    public long CustomerId { get; set; }

    public ICollection<BasketItem> BasketItems { get; set; }
}

Solution

  • I should not create a database manually

    I think we have some miss-understood here, on IMongoClient interface, it has a method GetDatabase that will create the database automatically on the server if it doesn't exists yet, so... basically, that kind of migration is automatic.

    database and collections must be created according to entities that I have created

    IMongoDatabase interface have GetCollection<YourEntityType>(Your collection name) that would generate the collection too as far as I can remember.(My code got fully worked, despite I'm not setting anything on the database).

    I think our most realistic case was create the index on the collection if it's doesn't exists yet.