0

I'm very new to Entity Framework. I'm trying to use it to query the database, and I want to set a string equal to the result of that query.

Here's the code I'm using:

string UserId = (db.StudentModel.Where(b => b.UserName == strCert)).ToString();

Now, obviously this sets UserId equal to the query. How do I set UserId equal to the result?

2
  • do you mean, how to get SQL query from LINQ query? Commented Jul 28, 2014 at 22:27
  • Am I incorrect in using the linq tag? I just want to use that query that I have above to get a cell from the database. The text in that cell is what I need UserId to store. Commented Jul 28, 2014 at 22:28

2 Answers 2

2

Do you mean something like this :

string UserId = db.StudentModel.FirstOrDefault(b => b.UserName == strCert).UserId;

or more safely :

var student = db.StudentModel.FirstOrDefault(b => b.UserName == strCert);
if(student != null) 
{
    string UserId = student.UserId;
    /* do something with UserId here */
}
Sign up to request clarification or add additional context in comments.

7 Comments

This is an excellent implementation but I don't see the value added in line 2.
Two questions: 1) when I use this, it's giving me a 'cannot implicitly convert int to string' error - I don't even know what the int would be! 2) Can you explain why UserId goes at the end of the command?
It's starting to look like UserId is of type int rather than the inexplicable string type that OP's sample code includes :D
1) you need to add .ToString() (edited my code as I didn't know before that UserId is of type int). 2) the query return a StudentModel -I guess the exact type- and you want only UserId property of that model, that's why .UserId at the end is required
WELL THAT'S EMBARRASSING. You're right. It's an int in the database. Much appreciated for pointing that out! hahaha
|
1

use this:

db.StudentModel.FirstOrDefault(b => b.UserName == strCert).UserId

but would be better to get object and check for null

var user = db.StudentModel.FirstOrDefault(b => b.UserName == strCert);

1 Comment

you will need to check if query returns null to avoid exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.