简体   繁体   English

从带有 Linq 表达式的 IMongoQueryable 集合中选择会引发错误 [c# 驱动程序 2.2.4]

[英]Selecting from a IMongoQueryable collection with a Linq Expression throws an error [c# driver 2.2.4]

Using the mongoDb c# driver 2.2.4, selecting from a IMongoQueryable collection with a Linq Expression throws an error because of my Id field.使用 mongoDb c# 驱动程序 2.2.4,从带有 Linq 表达式的 IMongoQueryable 集合中进行选择会因为我的 Id 字段而引发错误。 Here is the code:这是代码:

MongoDB.Driver.MongoClient myClient = new MongoDB.Driver.MongoClient("mongodb://localhost:27010");
            var db = myClient.GetDatabase("YOUR_MONGODB_DATABASE");
            var collection = db.GetCollection<Man>("Test");
            var queryableCollection = collection.AsQueryable();

            Man obj = new Man() {Id = "Man1_671", Name = "Patrick"};
            collection.InsertOneAsync(obj).Wait();
            // Insertion works fine

            System.Linq.Expressions.Expression<Func<Man, Man>> func = mec => new Man
            {
                Id = mec.Id,
                Name = mec.Name
            };

            // This line bugs using the 2.2.4 driver and works using the 2.2.1 version
            var listProjection = queryableCollection.Select(func).ToListAsync().Result;

Obviously I would have to rename my property to '_id' (tested, it works), but I don't get why it used to work (especially because it is stated that no breaking changes have been introduced).显然,我必须将我的属性重命名为“_id”(经过测试,它有效),但我不明白为什么它曾经有效(特别是因为它声明没有引入任何重大更改)。 Was I using a bug that had been fixed ?我是否使用了已修复的错误? Is it a bug in the driver ?这是驱动程序中的错误吗? Any help would be greatly appreciated :)任何帮助将不胜感激:)

Edit 1: exception thrown is : Element 'Id' does not match any field or property of class MongoDbHierarchicalStoring.Man.编辑 1:抛出的异常是:元素“Id”与类 MongoDbHierarchicalStoring.Man 的任何字段或属性都不匹配。

Regards, Florent问候, 佛罗伦萨

I've been able to work around this issue by using a class on top of the real type for the projection purposes:我已经能够通过在真实类型之上使用一个类来进行投影来解决这个问题:

internal class ProductProjection : Product
{ 
    [BsonIgnore]
    [JsonIgnore]
    public string _id { set => Id = value; }
}

It's then possible to project the aggregate query into this new type and implicitly cast it back:然后可以将聚合查询投影到这种新类型中并隐式地将其转换回:

List<Product> results = _collection.Aggregate().Match(queryFilter).Project(
    x => new ProductProjection
    {
        _id = x.Id,
        ....
    }).ToList();

The resulting Products contain any custom projections as well as the fully populated Id field.生成的产品包含任何自定义投影以及完全填充的 Id 字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM