.Net Core + MongoDb 根据实体自动创建数据库

.Net Core + MongoDb Create Database Automatically according to entities

我一直在从事 .Net Core 项目,我想使用 MongoDb 作为数据库实现。我已经创建了将创建为集合的实体。您可以看到下面的实体。

当我启动项目时,如果服务器上不存在数据库,则必须根据我创建的实体创建数据库和集合。我不应该手动创建数据库。

对于 Mssql,我在此过程中使用 FluentMigrator。我该如何处理 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; }
}

I should not create a database manually

我想我们在这里有一些误解,在 IMongoClient 接口上,它有一个方法 GetDatabase 如果数据库还不存在,它会在服务器上自动创建数据库,所以...基本上,这种迁移是自动的。

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

IMongoDatabase 界面有 GetCollection<YourEntityType>(Your collection name),据我所知,它也会生成集合。(尽管我没有在数据库上设置任何内容,但我的代码已完全运行)。

我认为我们最现实的案例是在集合上创建索引(如果集合尚不存在)。