I am trying to create and add a document to GCP Firestore using the .Net library for GCP: Google.Cloud.Firestore.V1 , however, I cannot figure out how to use the CreateDocumentRequest object to call the CreateDocumentAsync method. Here's a snippet of a method that takes in a document which is then passed to the CreateDocumentRequest. I attempt to cast the document object to type Document but I get an Invalid cast exception:
public async Task<Document> CreateDocumentAsync(object document,
CancellationToken cancellationToken = default)
{
var docRequest = new CreateDocumentRequest
{
Document = (Document)document,
CollectionId = _collectionName,
Parent = _collectionReference.Parent.Path
};
return await _fireStoreDb.Client.CreateDocumentAsync(
docRequest, cancellationToken);
}
How can I convert a custom object into type Google.Cloud.Firestore.V1 so that I may set the document data when creating the document?
The documentation for Google.Cloud.Firestore.V1 shows snippets that use it in the following way:
public async Task CreateDocumentRequestObjectAsync()
{
// Snippet: CreateDocumentAsync(CreateDocumentRequest, CallSettings)
// Additional: CreateDocumentAsync(CreateDocumentRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
CreateDocumentRequest request = new CreateDocumentRequest
{
Parent = "",
CollectionId = "",
DocumentId = "",
Document = new Document(),
Mask = new DocumentMask(),
};
// Make the request
Document response = await firestoreClient.CreateDocumentAsync(request);
// End snippet
}
My intent is to replace the "Document" property within the CreateDocumentRequest with my own document and add that to firestore.
I can see how it is done using the Google.Cloud.Firestore library as shown below:
public async Task AddAsync()
{
string projectId = _fixture.ProjectId;
// Sample: AddAsync
FirestoreDb db = FirestoreDb.Create(projectId);
// Create a document with a random ID in the "cities" collection.
CollectionReference collection = db.Collection("cities");
City city = new City
{
Name = "Los Angeles",
Country = "USA",
State = "CA",
IsCapital = false,
Population = 3900000L
};
// Alternatively, collection.Document("los-angeles").Create(city);
DocumentReference document = await collection.AddAsync(city);
// End sample
}
However, I would like to do the same using Google.Cloud.Firestore.V1 client library wrapper provided.