简体   繁体   中英

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?

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

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

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM