Linq

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
 
B

bruce barker

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)
 
J

James Page

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)
 
J

James Page

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?
 
R

rstrahl

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 ---
 
J

James Page

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 ---
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top