[英]C# MongoDB & Projection. Fails with serialization Exception
假設我有一個類似的收藏:
{
id: "1"
name: "collection 1"
properties: "Some properties."
}
以類表示為
[BsonIgnoreExtraElements]
public class InfoPOCO {
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("properties")]
public string Properties { get; set; }
}
現在,如果要創建一個像
Builders<InfoPOCO>.Projection.Include(_ => new{_.Name});
並與其他參數一起調用(無需投影即可正常工作)
return GetDataBase().GetCollection<InfoPOCO>(collectionName).Find(Expr).
Project<InfoPOCO>(projectionDefinition).Skip(Offset).Limit(Limit).Sort(sort).ToList<InfoPOCO>()
然后我得到以下錯誤:
System.InvalidOperationException : Unable to determine the serialization information for
_ => new <>f__AnonymousType2`1
Result StackTrace:
at MongoDB.Driver.ExpressionFieldDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.SingleFieldProjectionDefinition`1.Render(IBsonSerializer`1 sourceSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.KnownResultTypeProjectionDefinitionAdapter`2.Render(IBsonSerializer`1 sourceSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](IClientSessionHandle session, FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass35_0`1.<FindSync>b__0(IClientSessionHandle session)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
at MongoDB.Driver.FindFluent`2.ToCursor(CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
可能的原因是,當不使用投影時,它會提取整個集合。 我不知道是否需要映射類嗎? (認為自動地圖會接受)。 我也嘗試在類中構造構造函數。 但是還是一樣的錯誤。 任何幫助將不勝感激。 謝謝 !
我終於明白了! 是的,我知道,有點慢,du。
問題是,當我嘗試將其映射為:
Builders<InfoPOCO>.Projection.Include(_ => new{_.Name, _.Properties});
這是一個強類型的表達式,結果被映射到一個匿名類型。 如果在獲取時同時使用forEach,那么我可以獲得這些值。 因此,我現在使用的解決方案很簡單。 我將投影更改為:
Builders<InfoPOCO>.Projection.Include(_ => _.Name).
Include(_ => _.Properties);
這可行! 並不是說它是完美的解決方案或解釋,但我看到很多人都在為之苦苦掙扎,所以只提一個解決方法。 希望它可以幫助像我這樣的人避免經過數小時的谷歌搜索!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.