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

时间:2013-02-01 10:44:36

标签: c# mongodb

我有一个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);

1 个答案:

答案 0 :(得分:1)

给出一张地图:

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) { ... }

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