I’m trying to retrieve information from a contract. Saving info works just fine and it communicates well but when I try to retrieve the info it give this error:
unable to cast object of type 'system.object' to type 'system.collections.IList'
public async Task<string[]> GetAllPatientIdsAsync() {
var contract = _web3.Eth.GetContract(_abi, _contractAddress);
var getAllPatientIdsFunction = contract.GetFunction("getAllPatientIds");
try
{
var result = await getAllPatientIdsFunction.CallAsync<object>();
if (result is object[] objectArray)
{
string[] idsArray = objectArray.Select(x => x.ToString()).ToArray();
return idsArray;
}
else
{
MessageBox.Show($"Unexpected return type: {result.GetType()}.");
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
return null;
}
}
Here is the code of the Contract:
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract PatientRecord {
struct Patient {
string id;
string name;
string medicalHistoryHash;
}
mapping(string => Patient) private patients;
string[] private patientIds; // Array to store patient IDs
// Event to log the addition of a new patient
event PatientAdded(string id, string name, string medicalHistoryHash);
// Function to add a new patient
function addPatient(
string memory _id,
string memory _name,
string memory _medicalHistoryHash
) public {
// Check if the patient already exists
require(bytes(patients[_id].id).length == 0, "Patient already exists");
// Add the patient to the mapping
patients[_id] = Patient(_id, _name, _medicalHistoryHash);
// Add the patient ID to the array
patientIds.push(_id);
// Emit the event
emit PatientAdded(_id, _name, _medicalHistoryHash);
}
// Function to retrieve a patient's information
function getPatient(string memory _id) public view returns (string memory, string memory) {
// Check if the patient exists
require(bytes(patients[_id].id).length != 0, "Patient not found");
// Retrieve and return the patient's information
Patient memory patient = patients[_id];
return (patient.name, patient.medicalHistoryHash);
}
// Function to update a patient's medical history
function updateMedicalHistory(string memory _id, string memory _newMedicalHistoryHash) public {
// Check if the patient exists
require(bytes(patients[_id].id).length != 0, "Patient not found");
// Update the patient's medical history
patients[_id].medicalHistoryHash = _newMedicalHistoryHash;
}
// Function to retrieve all patient IDs
function getAllPatientIds() public view returns (string[] memory) {
return patientIds;
}
}
I kept asking ChatGPT but it stopped giving the same error, I should be able to retrieve the String IDs in the list