0

I have an unusual setup where I am inserting data into a MongoDB from a PHP site. The data is then read by .NET and served up as an API.

After inserting a record (via PHP) the .NET API throws the following error when trying to read the data.

An error occurred while deserializing the Id property of class Project.ModelClass: Cannot deserialize Guid from BsonType ObjectId.

The code doing the insert is:

    $item = Item::create(array(
        // fields
    ));

And the model class being read into has an Id field like this:

        public Guid Id { get; set; }

The API will correctly serve up other items in the same collection that have been imported from another datasource.

Do I need to do something special in the PHP insertion to allow the Id to be read and deserialised into the .NET model class?

Any help would appreciated!

Stuart

3
  • Can you show us what the MongoDB document inserted with PHP looks like?
    – Joe Waller
    Commented Aug 21, 2013 at 8:50
  • The PHP inserted Id looks like 'ObjectId("xxx...xx")' and the .NET one looks like 'BinData(3, "xxxx...xxx")'. Ideally I would like to keep the .NET one as is and change the PHP one to match.
    – Stuart
    Commented Aug 22, 2013 at 16:05
  • Can you give an example of what fields are being inserted by the PHP code? From your comments it sounds like you want to use a GUID as the _id for the document, but you haven't shown us what fields are actually being inserted by the PHP code (and it looks like the PHP code is inserting an ObjectId, not a GUID).
    – Joe Waller
    Commented Aug 26, 2013 at 7:33

2 Answers 2

1

From your comments it sounds like you want to use a GUID as the _id for the document, but you haven't shown us what fields are actually being inserted by the PHP code.

Assuming that is the case though, your PHP code will need to insert the _id as a GUID explicitly, otherwise the PHP driver will automatically set the _id field to a generated ObjectId.

$collection->insert(array(
    "_id" => new MongoBinData($guid, 3)
));

should set the _id to a GUID instead of the default ObjectId.

1
  • Thanks for the response - saving it as a "real" GUID seemed to get it all working.
    – Stuart
    Commented Aug 26, 2013 at 11:44
1

Try to replace Guid with ObjectId in C#

public ObjectId Id { get; set; }

Your Id field is stored as ObjectId type. And C# driver cannot deserialize ObjectId type to Guid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.