I have just 2 objects and simple query to retrieve the data.
The result of query which is stored in array ccList according to debug output is:
(
CustomThree__c:
{
Name=cusmei3 2,
customOne__c=a005000000IwnOPAAZ,
Id=a025000000FsFGQAA3
},
CustomThree__c:
{
Name=cusmei3 1,
customOne__c=a005000000IwnOUAAZ,
Id=a025000000FsFGLAA3
}
)
As you can see system.debug(ccList[0]) returns:
CustomThree__c:{
Name=cusmei3 2,
customOne__c=a005000000IwnOPAAZ,
Id=a025000000FsFGQAA3
}
But when I try to get Id (or other field) from the array, the error occurs.
Can anyone point out what am I doing wrong?
code
Object[] ccList;
ccList = [SELECT id, name, CustomOne__r.name FROM CustomThree__c];
system.debug(ccList);
system.debug('******************************************');
system.debug(ccList[0]);
system.debug(ccList[0].Id); //this one cause the error
I think you'll have to change the type of ccList from "Object" to "CustomThree__c". This will also give you compile-time checking when you'll try to write ccList[0].SomeNonExistentFieldName__c.
If you can't do it and really need the object that stores result to be generic - I believe this should be SObject?
Related
I want to check if a value exists in an array of objects.
My array looks something like this:
[
0: {
id: 'unique_obj_id',
item: {
id: 'unique_item_id',
...
},
...
},
1: {...}
]
The objects in the array can be one of many interface types (depending on my api call, here: resource strings represent these interfaces, which are defined somewhere else). But one array will always consist of the same interface types for a given data request.
I'm trying to write a reusable function to check whether given_id exists for any object in the array for obj.item.id.
So far I've managed to write the correct logic but typescript throws some exceptions that I can't seem to figure out. shopApprovalData is a collection of interfaces each following the above object structure accessible by the indices of resource.
export type ApprovalResource = 'str1' | 'str2' | 'str3' | 'str4' | 'str5';
export const checkApprovalItem = (given_id: string, resource: ApprovalResource) => {
const shopApprovalData = useShopApprovals();
if (shopApprovalData && shopApprovalData[resource]) {
const resourceApprovalData = shopApprovalData[resource];
if (resourceApprovalData.find(e => e.item.id === id)) {
return true;
}
}
return false;
}
Typescript shows me that shopApprovalData and itemApprovalData is possibly undefined and that the expression find() is not callable since signatures of members of the union type are not compatible with each other. (Apparently, some removes the error, why?)
What approach should I choose instead to check whether the given_id exists in any object of the array?
Based on your usecase, i create this code sandbox: https://codesandbox.io/s/stackoverflow-answer-ke9drk?file=/src/index.ts
explanation:
Type wont compile, so we need something to mark what the interface of the object.
Also i may confused by your code shopApprovalData[resource] what do you want to achieve here? for example, if resource is str1 shopApprovalData[resource] will always return undefined because no index str1 in Array
I hope it help,
Best Regards
public void search ()
{
string searchquery='select Car_Name__c ,id from car__c where Car_Name__c like \'%'+ searchkey+'%\' Limit 20';
sim=Database.query(searchquery);
}
System.QueryException: List has more than 1 row for assignment to SObject
Error is in expression '{!search}' in component apex:commandButton in page simpsons_vf01_car_show: Class.Simpsons_Cl1_classCar.search: line 36, column 1
Presumably the value sim is of type Car__c. You cannot assign the result of a query that returns anything other than exactly one record to a value whose type is an SObject. In particular, this does not make sense when you're performing a search query with a LIMIT 20 clause.
You should type your variable as a List<Car__c>.
I have an input where if a user searches for id and if it matches the id, it will display the status. But it gives me an error if a user doesn't give the right ID. What should I do so that even if the user searches for invalid it will just display "Invalid id".
My array
What my code looks like
According to your code, I have seen that
Array Looks like:
let Deliveries=[{DeliveryID:"WHKYYY", OwnerID:2, Staus:"Delivered"},
{DeliveryID:"MHKYYY", OwnerID:3, Staus:"Delivered"},
{DeliveryID:"KKHKYYY", OwnerID:4, Staus:"Warehouse"},
{DeliveryID:"LLHKYYY", OwnerID:2, Staus:"Delivered"},
]
Problem is that when you are searching for something and it is not matching with the DeliveryID that time search result will be undefined. You can use || to avoid the undefined values to set the empty array like [] and before return the staus you can check the rearch result. If the result is empty return "".
Code like :
let track =data.Deliveries.filter(item=> Model.searchQuery===item.DeliveryID)||[];
if(track .length>0){
//mathch the ID and informaiton is avialable
//other code here
}else{
// does not match. return null or ""
}
According to the Dapper documentation, you can get a dynamic list back from dapper using below code :
var rows = connection.Query("select 1 A, 2 B union all select 3, 4");
((int)rows[0].A)
.IsEqualTo(1);
((int)rows[0].B)
.IsEqualTo(2);
((int)rows[1].A)
.IsEqualTo(3);
((int)rows[1].B)
.IsEqualTo(4);
What is however the use of dynamic if you have to know the field names and datatypes of the fields.
If I have :
var result = Db.Query("Select * from Data.Tables");
I want to be able to do the following :
Get a list of the field names and data types returned.
Iterate over it using the field names and get back data in the following ways :
result.Fields
["Id", "Description"]
result[0].values
[1, "This is the description"]
This would allow me to get
result[0].["Id"].Value
which will give results 1 and be of type e.g. Int 32
result[0].["Id"].Type --- what datattype is the value returned
result[0].["Description"]
which will give results "This is the description" and will be of type string.
I see there is a results[0].table which has a dapperrow object with an array of the fieldnames and there is also a result.values which is an object[2] with the values in it, but it can not be accessed. If I add a watch to the drilled down column name, I can get the id. The automatically created watch is :
(new System.Collections.Generic.Mscorlib_CollectionDebugView<Dapper.SqlMapper.DapperRow>(result as System.Collections.Generic.List<Dapper.SqlMapper.DapperRow>)).Items[0].table.FieldNames[0] "Id" string
So I should be able to get result[0].Items[0].table.FieldNames[0] and get "Id" back.
You can cast each row to an IDictionary<string, object>, which should provide access to the names and the values. We don't explicitly track the types currently - we simply don't have a need to. If that isn't enough, consider using the dapper method that returns an IDataReader - this will provide access to the raw data, while still allowing convenient call / parameterization syntax.
For example:
var rows = ...
foreach(IDictionary<string, object> row in rows) {
Console.WriteLine("row:");
foreach(var pair in row) {
Console.WriteLine(" {0} = {1}", pair.Key, pair.Value);
}
}
private Incident incident = null;
incident = (Incident)(rdc.Incidents.Where(i => i.ID == ID));
I get the following exception:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[WPF.Incident]' to type 'WPF.Incident'.
I need an instance of Incident to use it like this:
IList listInjury = ((IListSource)incident.Incident_Injuries.OrderBy(m => m.Employee.LastName)).GetList();
Try:
incident = rdc.Incidents.First(i => i.ID == ID);
The Where method can return multiple results (probably not in your specific case, but in the general case it could), so you'll need to get the first (and presumably only) result with First method like Mehrdad described
The code
(Incident)(rdc.Incidents.Where(i =>i.ID == ID))
returns a sequence, IEnumerable<Incident> and you are trying to cast that to type of Incident.That's why you're getting InvalidCastException because those types are not compatible. As Mehrdad suggested, you can use First. However, First would throw an exception if the sequence does not contain any elements. This may or may not be desirable. If exception is not desirable, you can call DefaultOrEmpty which would return the default value for that type if the sequence contains no elements. If Incident is a reference type, the default value would be null and you should add a null check in your code and handle that case appropriately.