Linq

  • Thread starter Thread starter James Page
  • Start date Start date
J

James Page

Hi all I hope someone can help me out here:

I have a stored procedure which returns one row with two columns when it is
supplied with a userId parameter - this works fine and produces the results I
wished for.

However

I am writing a helper class that uses the stored procedure utilising LINQ -

Dim var1 = From db In myDb.mysproc(UserId) Select db.col1
Dim var2 = From db In myDb.mysproc(UserId) Select db.col2

Now what I need to do is use var1 & var2 elsewhere - but it appears that
when the code runs var1 & var2 hold the desired data output but returns as
'Nothing' when I try to access the two variables!

Any ideas?

VB.net /VS2008
 
var1 and var2 are queries (collections), the generated sql statement
will not be executed until you foreach the query to get the results
(actually it will be run everytime you foreach the query).

-- bruce (sqlwork.com)
 
Thanks bruce - do you have an example?

bruce barker said:
var1 and var2 are queries (collections), the generated sql statement
will not be executed until you foreach the query to get the results
(actually it will be run everytime you foreach the query).

-- bruce (sqlwork.com)
 
Sorted!

Here's what I did:

Dim myVar as String

Dim var1 = From db In myDb.mysproc(UserId) Select db.col1
For Each var1Result In var1
myVar = var1Result
Next

Just a thought - is this the correct method if the underlying query will
only ever return a single value?
 
If you're retrieving a single item or value you should probably use
..FirstOrDefault() on your result set. That gives you a single entity to work
with:

User user = (from usr in Context.Users where usr.UserId ==
userId).FirstOrDefault();

You'll get the first matched instance or null if no match is found.

Same applies for single values.

+++ Rick ---
 
Thanks Rick

I'll try that out over the weekend.

rstrahl said:
If you're retrieving a single item or value you should probably use
.FirstOrDefault() on your result set. That gives you a single entity to work
with:

User user = (from usr in Context.Users where usr.UserId ==
userId).FirstOrDefault();

You'll get the first matched instance or null if no match is found.

Same applies for single values.

+++ Rick ---
 
Back
Top