I'm trying to query some data and projecting to a class with fewer properties by sending an expression (C# mongo driver version 2.7.3). I am trying to understand why a specific expression fails. The failure greatly limits the user from writing a common projection and forces him to write the projection inline in every call. This is a simplified example:
private IMongoCollection<MyOriginalClass> _collection;
class MyOriginalClass // imagine this class has many more properties
{
public int ID { get; set; }
}
class MyProjectedClass
{
public int ID { get; set; }
}
void DoWork()
{
var data1 = GetData(lib => new MyProjectedClass { ID = lib.ID }); // succeeds
var data2 = GetData(lib => ToProjected(lib)); // Fails in mongo driver: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
}
IEnumerable<MyProjectedClass> GetData(Expression<Func<MyOriginalClass, MyProjectedClass>> projection)
{
return _collection
.Aggregate()
.Project(Builders<MyOriginalClass>.Projection.Expression(projection))
.ToList();
}
MyProjectedClass ToProjected(MyOriginalClass orig)
{
return new MyProjectedClass {ID = orig.ID};
}