13

So we all know it is possible to directly select into a Map, like this:

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

Is it possible to do the same thing, using Database.query()?

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

Sadly the latter doesn't seem to work.

3 Answers 3

22

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?

1
  • Since you were first by 6 seconds - I'll accept yours. :)
    – Semmel
    Commented Nov 20, 2018 at 10:23
11

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'));
4
  • 6
    Ha! Beat you by 6 seconds. Just long enough to crack open a beer with my lovely deployment fish bottle opener :)
    – Charles T
    Commented Nov 15, 2018 at 17:47
  • 🤨 I saw that quick edit in the 5 minute window. :) Commented Nov 15, 2018 at 17:48
  • 2
    Hah yes, just a formatting gaffe.
    – Charles T
    Commented Nov 15, 2018 at 17:51
  • I could swear that I tried casting it but - but obviously I didn't. It's working now.
    – Semmel
    Commented Nov 20, 2018 at 10:22
10

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

You must log in to answer this question.

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