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> {


//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'; 

//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));
  • Did you manage to resolve your issue? Apr 7, 2015 at 9:39

1 Answer 1


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>(

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .