FindOneByIdAs,具有 ObjectId 的字符串表示形式

本文关键字:表示 字符串 具有 ObjectId FindOneByIdAs | 更新日期: 2023-09-27 17:56:53

我对ObjectId表示有一个小问题。下面是示例代码:

public class EntityWithObjectIdRepresentation
{
    public string Id { get; set; }
    public string Name { get; set; }
}
[Test]
public void ObjectIdRepresentationTest()
{
    BsonClassMap.RegisterClassMap<EntityWithObjectIdRepresentation>(cm =>
    {
        cm.AutoMap();
        cm.GetMemberMap(x => x.Id).SetRepresentation(BsonType.ObjectId);
    });
    var col = db.GetCollection("test");
    var entity = new EntityWithObjectIdRepresentation();
    col.Insert(entity);
    Assert.IsNotNullOrEmpty(entity.Id); // Ok, Id is generated automatically
    var res = col.FindOneByIdAs<EntityWithObjectIdRepresentation>(entity.Id);
    Assert.IsNotNull(res); // Fails here
}

上面的代码适用于

var res = col.FindOneByIdAs<EntityWithObjectIdRepresentation>(ObjectId.Parse(entity.Id));

但是我想要的是将这些东西抽象在通用存储库类中,所以通常我不知道这个 Id 是否必须转换为 ObjectId。我可以从 BsonClassMap 检索此类信息吗?

以下代码也可以工作,但由于 LINQ 表达式转换,根据基准测试,它几乎慢了 15 倍:

var res = col.AsQueryable().FirstOrDefault(x => x.Id.Equals(id));

好的,我包含来自项目的实际代码:

 public class MongoDbRepository<T, T2> : IRepository<T, T2>
    where T : IEntity<T2> // T - Type of entity, T2 - Type of Id field
{        
    protected readonly MongoCollection<T> Collection;
    public MongoDbRepository(MongoDatabase db, string collectionName = null)
    {
        MongoDbRepositoryConfigurator.EnsureConfigured(db);   // Calls BsonClassMap.RegisterClassMap, creates indexes if needed  
        if (string.IsNullOrEmpty(collectionName))
        {
            collectionName = typeof(T).Name;
        }
        Collection = db.GetCollection<T>(collectionName);
    }
    public T GetById(T2 id)
    {
        using (Profiler.StepFormat("MongoDB: {0}.GetById", Collection.Name))
        {
            // TODO Use FindOneByIdAs<T>
            return Collection.AsQueryable().FirstOrDefault(x => x.Id.Equals(id));
        }
    }
    // some more methods here ...
}
// ...
var repo = new MongoDbRepository<SomeEntity,string>(); // Actually it's injected via DI container
string id = "510a9fe8c87067106c1979de";
// ...
var entity = repo.GetById(id);

FindOneByIdAs,具有 ObjectId 的字符串表示形式

给定一个地图:

var classmap = BsonClassMap.LookupClassMap(typeof(T));
// // This is an indexed array of all members, so, you'd need to find the Id
var member = map.AllMemberMaps[0]; 
var serOpts = ((RepresentationSerializationOptions).SerializationOptions);
if (serOpts.Representation == BsonType.ObjectId) { ... }

使用上述基本逻辑,可以确定成员的序列化类型。