質問

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

役に立ちましたか?

解決

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.

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top