function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mpatelmpatel 

Help with System.QueryException: List has no rows for assignment to SObject

What I am trying to do is determine if a Lead or Contact exist and they don't then add them as a new Lead.

 

Here is the Apex Class

 

global class getcontactinfo {

 Webservice static Contact getcontactemail(string Contact) {
 contact c = [Select Phone,Email from Contact where Email = :Contact];
 
    return c;
}
}

 

 

So what I am doing to calling this global class from within ASP.net VB.

 

If the users e-mail does not exist it is giving me this error : System.QueryException: List has no rows for assignment to SObject.

 

If the users e-mail does exist then I am getting this error : System.QueryException: List has more than 1 row for assignment to SObject

 

I need to get a value passed back to my ASP.net page so that I can either add them using the Web2Lead or not add them as a lead cause there e-mail exist already.

 

 

 

AmphroAmphro

The query is returning a list of contacts which can't be assigned into a single sObject. Try this

 contact c = [Select Phone,Email from Contact where Email = :Contact limit 1];

 Just careful that's what you really want. i.e. what do you want to happen if their are two contacts have the same e-mail?

mpatelmpatel

If there are two emails listed then I only want it to return it once, so I can evaluate it via ASP.net.

 

 

NOTSOFASTNOTSOFAST

try initializing the variable before populating it from soql:

 

  contact c = new Contact();

  c = [Select Phone,Email from Contact where Email = :Contact limit 1];

 

and/or enclose your soql in try/catch block.

ArtoArto

How about creating an array for all matching records?

 

contact[] c = [Select Phone,Email from Contact where Email = :Contact]; 

mpatelmpatel

Can you show me full examples of how to put it into an Array and The Try and Catch block?

 

 

Also, how do I get the variable or array in ASP.net?

 

 

thanks

ArtoArto

I would try something like this:

 

  global class getcontactinfo {

 

  Webservice static Contact getcontactemail(string Contact) {

  contact tmp;

  for(contact[] c : [Select Phone,Email from Contact where Email = :Contact]){

  tmp = c;

  }

  return tmp;

}

}

 

 

 

mpatelmpatel

I tried the code above but it's giving me an error when trying to save the Apex Class.

 

Error: Compile Error: Illegal assignment from LIST:SOBJECT:Contact to SOBJECT:Contact at line 12 column 3 

AmphroAmphro

That code is now trying to assign an sObject in a list. If you use a for each loop, you need to do it like this. 

for (Contact c : [select Name from Contact]) {
   temp = c;}