Mark S
Mark S

Reputation:

Incorrect results, what am I doing wrong?

I have the following simple LINQ to SQL statement:

string strUserID = Eval("whoInsert").ToString();

insLusHmoobDataContext userDataContext = new insLusHmoobDataContext();

var userName = from usr in userDataContext.Users
               where usr.UserId.Equals(strUserID)       
               select usr.UserName;

return userName.ToString();

Instead of showing me the UserName from the aspnet_Users table, it showed me the SQL select statement. Any idea?

Upvotes: 3

Views: 112

Answers (3)

Singleton
Singleton

Reputation: 3679

var userName = (from usr in userDataContext.Users where usr.UserId.Equals(strUserID)     
select usr.UserName).SingleOrDefault();

That's assuming there's going to be a single user for that ID, else you could use FirstOrDefault().

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062780

You need to add .Single().ToString();

Otherwise you haven't actually executed the query - you ate reporting the query itself.

Upvotes: 4

Jesper Larsen-Ledet
Jesper Larsen-Ledet

Reputation: 6723

userName is a LINQ to SQL expression tree which evaluates to the SQL query when converted to a string.

You probably want userName.First().ToString() instead;

That way the query is executed and you get the first value returned. You may want to use FirstOrDefault() and check for null values to be sure of not crashing :)

Upvotes: 2

Related Questions