My team was given a sample file that demonstrates how to interface with CosmosDB in C# and convert resulting Microsoft.Azure.Document
instances into POCOs. The documents are converted like this: (Ellipses indicate left out logic for concision)
public Task<T> GetItemAsync<T> (...)
{
Document document = await client.ReadDocumentAsync(...);
return (T)(dynamic)document;
}
It appears to me that (dynamic)document
somehow serializes the document which would otherwise need to be done by specifying each JSON field individually. Seeing as how dynamic
cast operations cannot be overloaded, I am at a loss as to what causes this deserialization to occur.
What am I overlooking that is preventing me from understanding this operation?
There is a misconception here about what is actually happening behind the scenes.
Some background first
ReadDocumentAsync
returns a DocumentResponse<Document>
which wraps a Document
containing the read resource record.
DocumentResponse<Document>
in turn has an implicit operator
that that allow it to be converted/cast to Document
hence
Document item = await client.ReadDocumentAsync<T>(...);
//replaced var for to Document for demonstrative purposes.
Document
is derived from IDynamicMetaObjectProvider
public class Document : Microsoft.Azure.Documents.Resource, System.Dynamic.IDynamicMetaObjectProvider
// Inheritance: Object --> JsonSerializable --> Resource --> Document
// Implements: IDynamicMetaObjectProvider
Represents a dynamic object, that can have its operations bound at runtime.
epmhasis mine
It is because of the IDynamicMetaObjectProvider
that it is first cast to dynamic
and then to the desired type.
Behind the scenes the dynamic resource object will try to bind the contained members of the parsed document to that of the target strongly typed object.
Saves you having to try and write an explicit conversion yourself for your desired types.
You could have also used the generic overload as suggested in another answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With