Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb:Fail to get GridFSFileInfo by ObjectID, but succeed by filename

Tags:

c#

mongodb

gridfs

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

like image 461
Kevin Yen Avatar asked Nov 03 '15 09:11

Kevin Yen


1 Answers

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?

like image 168
Paul Avatar answered Nov 15 '22 02:11

Paul