How to use dynamic SOQL to instantiate a MAP

I’ve tried doing it, but I get this error: Compile error at line 101 column 32
Invalid initial type List<SObject> for Map<Id,Opportunity>

Here’s my code:

//build out the set
set <id> opps = new set <id> {
'006a0000016wQyCAAU',
'006a0000016wQNlAAM',

};


//build out query

Map<String, Schema.SObjectField> fldObjMap = schema.SObjectType.Opportunity.fields.getMap();        
List<Schema.SObjectField> fldObjMapValues = fldObjMap.values();
String theQuery = 'SELECT ';        
for(Schema.SObjectField s : fldObjMapValues)        {           
    String theName = s.getDescribe().getName();           
    // Continue building your dynamic query string           
    theQuery += theName + ',';       
 }       
  theQuery += ' account.name, ';    
      // Finalize query string       
theQuery += ' FROM Opportunity where id IN :opps'; 
system.debug(thequery.length());      


//get opps
//This line works....
//Map <Id, Opportunity> oppMap = new Map<id, Opportunity>([select id from opportunity where id in :opps]);


//this line does not work...
Map <Id, Opportunity> oppMap = new Map<id, Opportunity>(Database.query(theQuery));

Answer

Database.query(String) returns a List<sObject> rather than a List<Opportunity> like your query does.

You need to cast the result of Database.query(String) before you can use it to populate a map using the Map<ID, sObject>(List<sObject>) constructor for a concrete sObject type.

Here is an example using your code:

Map <Id, Opportunity> oppMap = new Map<Id, Opportunity>(
    (List<Opportunity>)Database.query(theQuery)
);

Attribution
Source : Link , Question Author : PartOfTheOhana , Answer Author : Alex Tennant

Leave a Comment