Search code examples
c#mysqlentity-frameworklinqlinq-to-entities

MySqlContext how to write query to variable


I have a Mysqlcontext from which im doing queries. However, i dont know how these queries work, since i normally do the standard calls e.g. "select from where".

These are slightly different, and in this case i try to fetch an id from my db.Users. Unfortunately, it cant write my UserId to a variable?

var id = db.Users.Where(u => u.Email == email).Select(u => u.UserId);

it just returns null. How is this done correctly, and where can i find more documentation on how these queries work?

This is my updated code:

var id = db.Users.Where(u => u.Email == email).Select(u => u.UserId);
var materializeId = id.ToList();
int UserId = materializeId[0];

This actually seems to be working. Im however still confused that i have to fetch my item from a list, when there is only 1 matching ID? (There will be in all cases)

Cant i somehow query just a single id and write it to an int variable?


Solution

  • I would do something like this:

    var userId = (from u in db.Users where u.Email == email select u.Id).FirstOrDefault();