0

I created a simple Login Form in C# with entity framework. I keep getting this error in the if statement where it calls query.SingleOrDefault

Error   CS0103  The name 'Query' does not exist in the current context  rooster 

im relatively new to this, how do i fix this error?

My Code:

    private void btnLogin_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtEmail.Text))
        {
            // check voor invoeren van wachtwoord en email.
            MessageBox.Show("Voer u email adres in!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtEmail.Focus();
            return;
        }
        try
        {
            using (roosterAppEntities db = new roosterAppEntities())
            {
                var query = from u in db.Users
                            where u.username == txtEmail.Text && u.password == txtPassword.Text
                            select u;                                         
            }
            if (query.SingleOrDefault() != null)
           {
                MessageBox.Show("Succesvol ingelogd! ", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
           }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            throw;
        }


    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36

1 Answers1

0

You are initializing the variable query inside a USING(). As soon as your code disposes your db context, querywill be lost too. Please define it outside the using.

Here on SO is a very good question about the C# function of USING, please take a look.

Example:

    try
    {
        IQueryable query = null;
        using (roosterAppEntities db = new roosterAppEntities())
        {
            query = from u in db.Users
                        where u.username == txtEmail.Text && u.password == txtPassword.Text
                        select u;                                         
        }
        if (query.SingleOrDefault() != null)
       {
            MessageBox.Show("Succesvol ingelogd! ", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
       }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        throw;
    }
Cataklysim
  • 637
  • 6
  • 21