0

I'm beginner in web service and want to write simple query with LINQ to SQL and return that query result with Web Service,write this code:

[WebMethod]
public  string LinqExample()
{
    string conn = "Data Source=REMOVETHIS";
    DataClasses1DataContext behzad = new DataClasses1DataContext(conn);
    string result;
    var query = (from p in behzad.CDRTABLEs
                 where p.name == "behzad".Trim()
                 select p).Take(1);

    return query.ToString();
}

But when I run that web service,I get this error:

enter image description here

How can I solve that?

2
  • 2
    Seems your connection string is incorrect. Commented Jan 25, 2016 at 7:03
  • @user2946329 yes,i change that connection string and work it. Commented Jan 25, 2016 at 7:06

1 Answer 1

1

Three things:

1.) It seems your connection string is wrong, because there is a problem establishing the connection, not executing the query.

2.) You should not use Take(1), which returns an IEnumerable, but FirstOrDefault. You use Take if you want to take the first n elements, but First or FirstOrDefault if you only want exactly one result element.

3.) If using FirstOrDefault so, you have to do a null-check on returning: return query == null ? "" : query.ToString()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.