Reputation: 568
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:
How can I solve that?
Upvotes: 0
Views: 692
Reputation: 12648
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()
Upvotes: 1