You need to sign in to do that
Don't have an account?
Patrick G. Brown
Need assistance with System.QueryException: List has no rows for assignment to SObject
I have a very simple query that ls looking querying Accounts to find one particular Account, then assign that Account's ID to the Account field on my Contact record. I continue to get the "System.QueryException: List has no rows for assignment to SObject" error, but when I run the query using Query Editor, it returns the appropriate record. Can anyone please tell me what I'm doing wrong?
trigger assignAccounttoContact on Contact (before insert, before update) { Account a = [ SELECT ID, Name FROM Account WHERE Name = 'TestAccount' ]; for(Contact c: Trigger.new){ c.AccountID = a.ID; } }
trigger assignAccounttoContact2 on Contact (before insert, before update) {
List<Account> a = [ SELECT ID, Name FROM Account WHERE Name = 'TestAccount' ];
for(Contact c: Trigger.new) {
if (a.size() > 0)
c.AccountID = a[0].ID;
}
}
You are trying to access the field from a list, though it should be accessed from a record.
This will Help you : And don't use if check in for loop every contacts .
However, I'm still getting a "System.QueryException: List has no rows for assignment to SObject" error. I simply can't understand why it's happening. When I run this query directly, it works fine:
When I execute my test, it fails:
Let us know if that will help you