views:

185

answers:

2

How can I test a LINQ Query such as the following:

var vUser = (from u in this.dcLAUNCHOnline.aspnet_Users
                         where u.UserName.Equals(this.wCreateUser.UserName)
                         select u).Single();

I keep getting a null exception for vUser, however I am positive such a user exists.

+2  A: 

Use SQL profiler and see what SQL is fired by your code. You can try LinqPad too to run linq query against a DB.

Raj
Trying LINQPad - that might do the trick!
stringo0
+2  A: 

The record would have to exist or the exception would have to be thrown during evaluation of the lambda, otherwise the exception thrown would be to the effect of

The sequence contains no elements.

Are you accessing any properties on the vUser object after the query or is the this.wCreateUser object possibly null?

Edit: for comments..

If the exception is that the sequence contains no elements, the query being generated is not returning a result. I would recommend you examine the query being generated and test it directly against the SQL Server..

You can do this a few ways.

  1. Open SQL Profiler and watch the query being executed.
  2. Attach a TextWriter to the DataContext.Log so you can see the output of the query (example below)..
  3. Use LINQPad as the other answer suggested.

.

StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
this.dcLAUNCHOnline.Log = writer;
//Execute Query..
//sb.ToString(); //will contain the sql produced by the LINQ Query
Quintin Robinson
I do get the "The sequence contains no elements." error.this.wCreateUser is not null - I have a watch variable on it in visual studio :(
stringo0
Thanks for the detailed reply!
stringo0
No problem, I hope you get your issue resolved.
Quintin Robinson
Solution 2 worked in figuring out the sql!
stringo0
Good deal! That's a solution I commonly use to log and reproduce queries.
Quintin Robinson