5

I fail to get GridFSFileInfo by ObjectID, but succeed by filename, and the error message is: Unable to determine the serialization information for x=>x.Id

string objectID = ObjectIDTxt.Text.Trim();
GridFSBucketOptions bucketOptions = new GridFSBucketOptions();
bucketOptions.BucketName = "myBucket";

ObjectId gridfsObjectID = new ObjectId(objectID);

//by filename will succeed
//var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "myfilename.pdf");
//by ObjectID will fail
var filter = Builders<GridFSFileInfo>.Filter.Eq(x=>x.Id,gridfsObjectID);

var findOptions = new GridFSFindOptions();
findOptions.Limit = 1;

var myBucket = new GridFSBucket(_database, bucketOptions);

using (var taskOfCursor = Task.Run(() => myBucket.FindAsync(filter, findOptions)))
{   
    var taskOfList = Task.Run(() => taskOfCursor.Result.ToListAsync());
    GridFSFileInfo fileInfo = taskOfList.Result.FirstOrDefault();
    if (fileInfo != null)
    {
        FileNameLbl.Text = fileInfo.Filename;
    }
}

I'm using Mongodb 3.0,c# driver 2.1,wird tiger storage engine. Forgive me about the use of many 'Task.Run()',because for some reason I need to sync call async mongo methods. Any suggestions will be appreciated... thx

Kevin Yen
  • 78
  • 2
  • 6

2 Answers2

12

Unable to determine the serialization information for x=>x.Id

As the error suggests, you can't use x.Id inside your query in this way. The lambda expression provided is used to retrieve the name of the property and it doesn't understand what x.Id is.

You may try this:

var filter = Builders<GridFSFileInfo>.Filter.Eq("_id", gridfsObjectID);

which uses this overload of the Eq method and performs the implicit conversion from String to FieldDefinition.

Expressions seem a bit puzzling for me as well, but you may find more information related to Expression in the answers to this question: Why would you use Expression> rather than Func?

Community
  • 1
  • 1
Paul
  • 1,224
  • 2
  • 14
  • 31
  • It works! Thx for the answer and other information above. Although they seem to be a little difficult for me(especially the link of the Eq and the implicit conversion). I'll spend some time on them.Thx again. – Kevin Yen Nov 04 '15 at 03:12
0

You can add the lambda syntax directly in Find method:

myBucket.FindAsync(x => x.Id == new MongoDB.Bson.ObjectId(objectID), findOptions)
  • 2
    I tried this and got compiling error.Error message: could not convert lambda expression to MongoDB.Driver.FilterDefinition, because it is not delegate. And this is the api of FindAsync:[link](http://api.mongodb.org/csharp/2.1/html/M_MongoDB_Driver_GridFS_GridFSBucket_FindAsync.htm). FindAsync does not seem to accept lambda expression parameter. – Kevin Yen Nov 04 '15 at 02:35