Select into Map using Database.query()

It could be that this is one scenario where the "magic casting" of Database.query doesn't work quite right.

How about:

Map<Id, Account> accounts = new Map<Id, Account>((List<Account>)Database.query('SELECT Id, Name FROM Account'));

Any luck?


If you cast it to a List of the expected sObject type first it will work.

E.g.

Map<Id, Account> accounts = 
    new Map<Id, Account>((List<Account>)Database.query('SELECT Id, Name FROM Account'));

Adding a bit of info here on top of other answers.

This works:

Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account]);

Because the return type from the SOQL is that of Account.

This does not work:

Map<Id, Account> accounts = new Map<Id, Account>(Database.query('SELECT Id, Name FROM Account'));

Because the return type of Database.query is always SObject[]. So unless you cast the return type to the exact object type, it won't work.


Working versions.

Use SObject in your declaration

Map<Id, SObject> accounts = new Map<Id, SObject>(Database.query('SELECT Id, Name FROM Account'));

OR

As in other answers, cast it to list/array of account:

Map<Id, Account> accounts = new Map<Id, Account>((Account[])Database.query('SELECT Id, Name FROM Account'));