Mongodb C#驱动程序,如何使用表达式语法查找具有get-only属性的Object

本文关键字:get-only 属性 Object 查找 语法 驱动程序 表达式 何使用 Mongodb | 更新日期: 2023-09-27 18:28:01

域对象如下:(注意Age属性仅为get)

public class Person
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Age
    {
        get
        {
            return age;
        }
    }
    private int age;
    public Person(int age)
    {
        this.age = age;
    }
}

这是我的测试初始化代码:

    private static IMongoClient client;
    private static IMongoDatabase mongoDb;
    [ClassInitialize]
    public static void Initialize(TestContext testContext)
    {
        client = new MongoClient();
        mongoDb = client.GetDatabase("test");
        BsonClassMap.RegisterClassMap<Person>(cm =>
        {
            cm.AutoMap();
            cm.MapField("age").SetElementName("Age");
        });
        var person = new Person(10);
        person.Name = "abai";
        var collection = mongoDb.GetCollection<Person>("persons");
        collection.InsertOne(person);
    }

以下测试将通过:

    [TestMethod]
    public async Task FindPersonByNameTest()
    {
        var collection = mongoDb.GetCollection<Person>("persons");
        var result = await collection.Find<Person>(p => p.Name == "abai").ToListAsync();
        Assert.IsNotNull(result.FirstOrDefault());
    }

但此测试将失败:

    [TestMethod]
    public async Task FindPersonByAgeTest()
    {
        var collection = mongoDb.GetCollection<Person>("persons");
        var result = await collection.Find<Person>(p => p.Age == 10).ToListAsync();
        Assert.IsNotNull(result.FirstOrDefault());
    }

异常消息如下:

System.InvalidOperationException: {document}.Age is not supported.
Result StackTrace:  
at MongoDB.Driver.Linq.Translators.PredicateTranslator.GetFieldExpression(Expression expression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(BinaryExpression binaryExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate[TDocument](Expression`1 predicate, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.ExpressionFilterDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
   at MongoDB.Driver.MongoCollectionImpl`1.FindAsync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
   at MongoDB.Driver.FindFluent`2.ToCursorAsync(CancellationToken cancellationToken)
   at MongoDB.Driver.IAsyncCursorSourceExtensions.<ToListAsync>d__16`1.MoveNext()

似乎是get-only Age属性导致了异常。如何使用表达式语法查找具有get-only属性的Person对象?谢谢你的帮助!

Mongodb C#驱动程序,如何使用表达式语法查找具有get-only属性的Object

您愿意去掉backing字段,转而向Age添加一个私有setter吗?如果是这样的话,像这样的东西可能会起作用:

public class Person
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Age { get; private set; }
    public Person(int age)
    {
        Age = age;
    }
}

然后,在ClassMap 中

BsonClassMap.RegisterClassMap<Person>(cm =>
{
    cm.AutoMap();
    cm.MapProperty(p => p.Age);
});