如何在 C# .Net 中使用 InsertOneAsync 将文档插入 MongoDB 和 return 同一文档或其 ID

How to Insert document to MongoDB and return the same document or it's ID back using InsertOneAsync in C# .Net

我正在编写一个通用方法来充当数据访问层,使用 C# .Net 将文档插入 MongoDB。我的方法如下所示。这里的集合是从 MongoDB.

检索到的 MongoCollection
public async T Create(T entity){
await Collection.InsertOneAsync(entity);
}

我想要 return 插入的实体或其由 MongoDB 自动生成的 ID。 InsertOneAsync 方法正在 return 执行任务。我尝试如下更改它。但是它的 return 类型是无效的。

Collection.InsertOneAsync(entity).GetAwaiter().GetResult();

有没有办法使用 InsertOneAsync 方法取回 ID 或实体。我正在为 C# 使用 MongoDB 驱动程序。

生成 MongoDB 中的 ID on the client side

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

在您的情况下,您可以手动生成 ObjectId 并从您的方法(使用 ObjectId.GenerateNewId())或 return 整个对象中 return 它们,因为 MongoDB 驱动程序将设置正确的 _id如果使用 [BsonId] 属性

的值
public async Task<T> Create(T entity) where T:class
{
    await Collection.InsertOneAsync(entity);
    return entity;
}

并传递一个类型参数,如:

public class MyClass
{
    [BsonId]
    public ObjectId Id { get; set; }
    //other properties
}

一个好的解决方案是让客户端为您生成 _id

public class MyEntity
{
    [BsonId(IdGenerator = typeof(ObjectIdGenerator))]
    public ObjectId Id { get; set; }

    public string SomeStringProperty { get; set; }
    public DateTime SomeDateTimeProperty { get; set; }
}

每当在数据库中插入具有空 _id 的实体时,都会生成 _id,并且由驱动程序在插入之前提供 _id 值。

如果您不想在您的域模型中引用 MongoDB 库(我更喜欢这样),您可以简单地定义您的实体如下。

public class MyEntity
{
    public string Id { get; set; }

    public string SomeStringProperty { get; set; }
    public DateTime SomeDateTimeProperty { get; set; }
}

然后,直接在持久层中使用此代码将您的实体与数据库映射。

BsonClassMap.RegisterClassMap<MyEntity>(cm =>
{
    cm.AutoMap();
    cm.MapIdMember(c => c.Id)
        .SetIdGenerator(StringObjectIdGenerator.Instance)
        .SetSerializer(new StringSerializer(BsonType.ObjectId));
});

string ID 在代码中更容易处理,尽管这样它们在数据库中被映射为 ObjectId

注意:如果您使用异步版本的InsertOne()方法,您必须至少等待插入开始,然后才能获得驱动程序设置的_id值。