[SalesForce] SOQL query with Map keyeset

I need help in correcting this code.newbie to apex.I want to remove sessions with matching session_id__c from TrainSessions.I have written code like this

map<String, GED__c> NonGEDs= new map<string, GED__c>([SELECT  Session_Id__c FROM GED__c WHERE  User_Id__c = :userid AND Device__c = 'N']);

TrainSession[] removesessions = [SELECT Id FROM TrainSession WHERE ParentId = NULL and SessionType != 'GA' and UsersId = :userid  and  Id in :NonGEDs.keyset() ORDER BY CreatedDate DESC];

First query session_id__c is Text field map key datatype is string. but i need to use that against id field in second query as part of IN clause. How can I do it? Thanks for help.

Best Answer

There's no way to automatically populate a map of SObject records as you're trying to do in the first line.

However, assuming Session_Id__c contains only null values and legal Id values (either 15 or 18 characters), you can make a map of AggregateResult values to automatically convert the field to Id values:

Map<Id, AggregateResult> NonGEDS = new Map<Id, AggregateResult>(
    [SELECT Session_Id__c Id
     FROM GED__c
     WHERE User_Id__c = :userId AND Device__c = 'N'
     GROUP BY Session_Id__c]);

TrainSession__c[] removesessions = 
    [SELECT Id FROM TrainSession__c 
     WHERE  ParentId__c = NULL AND 
            SessionType__c != 'GA' AND 
            User_Id__c = :userid AND
            Id in :NonGEDs.keyset()
     ORDER BY CreatedDate DESC];

Note that the grouped field must be aliased to the literal field value Id in order for the map to work correctly.

Related Topic