【发布时间】:2018-07-11 17:40:53
【问题描述】:
我有一个使用 MongoDB 的 .NET 应用程序,所以我使用的是 mongo c# 驱动程序。我使用的当前版本是 1.9.2。
我正在尝试将其更新为最新的 C# mongodb 驱动程序 - 2.7.0。到目前为止,我不得不进行大量代码更改以进行重大更改。我现在被一些问题难住了 - 可能会在适当的时候为其他人提出新问题,但下面的问题导致应用程序在调试时甚至无法加载。
这是我使用 1.9.2 驱动程序的原始代码:
/// <summary>
/// Since the current Mongo driver does not support database side Select
/// projections, we need to use this custom function to achieve the same.
/// </summary>
/// <param name="criteria"></param>
/// <param name="fields"></param>
/// <returns></returns>
public IEnumerable<T> Get(Expression<Func<T, bool>> criteria,
params Expression<Func<T, object>>[] fields)
{
return this.Collection.FindAs<T>(Query<T>.Where(criteria)).SetFields
(Fields<T>.Include(fields));
}
这是我尝试使用最新的 C# 驱动程序:
/// <summary>
/// Since the current Mongo driver does not support database side Select
/// projections, we need to use this custom function to achieve the same.
/// </summary>
/// <param name="criteria"></param>
/// <param name="fields"></param>
/// <returns></returns>
public IEnumerable<T> Get(Expression<Func<T, bool>> criteria,
params Expression<Func<T, object>>[] fields)
{
return this.Collection.Find<T>(criteria).Project(Builders<T>.Projection.Include(FilterDefinitionBuilder<T>.(fields)));
}
但是,我在 .(fields))) 上收到红色构建错误;说不正确的主要表达,但不确定正确的解决方法是什么。
更新
我在下面添加了来自 mickl 答案的代码,现在在运行应用程序时出现以下异常:
"An error occurred while deserializing the Id property of class MyApp.Domain.Models.EntityBase: Cannot deserialize a 'String' from BsonType 'ObjectId'."
我的旧 C# Driver Mongo 代码有一个 BsonClassRegistration 类 - 其中的原始代码如下:
BsonClassMap.RegisterClassMap<EntityBase>(cm =>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
cm.GetMemberMap(c => c.Id).SetRepresentation(BsonType.ObjectId);
});
为了通过升级到最新的 C# 驱动程序来解决此问题,我将代码更改为以下内容:
BsonClassMap.RegisterClassMap<EntityBase>(cm =>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
cm.GetMemberMap(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
});
这是否是我现在在 Get 方法中看到的失败的原因
【问题讨论】:
标签: c# .net mongodb mongodb-.net-driver