简体   繁体   中英

LINQ to SQL Not Equals not working in Select statement

I am having trouble with getting a 'not equals' to work in a LINQ to SQL select statement.

I have three radio buttons for a Search function for my recipe program, Regular, Healthy, and All. The recipes have a field called Healthy, and the only way it is accessed is through the program, and the only thing it can have is NULL or Healthy.

The search button code is below. The Healthy and All work fine, but the rbRegRecipes doesn't show any recipes at all.

This is not a join, all fields are from the Recipe table.

private void bnSearchRec_Click(object sender, EventArgs e)
        {
            string srch = txtSearchRec.Text;
            using (RecipeClassesDataContext dbContext = new RecipeClassesDataContext())
            {
                if (rbRegRecipes.Checked == true)
                {
                    var reclist = from r in dbContext.Recipes where r.Name.Contains(srch) && (!r.Healthy.Equals("Healthy")) select r;
                    dgvRecipes.DataSource = reclist;

                }
                else if (rbHlthRecipes.Checked == true)
                {
                    var reclist = from r in dbContext.Recipes where r.Name.Contains(srch) && (r.Healthy == "Healthy") select r;
                    dgvRecipes.DataSource = reclist;
                }
                else
                {
                    var reclist = from r in dbContext.Recipes where r.Name.Contains(srch) select r;
                    dgvRecipes.DataSource = reclist;
                }
            }
        }

I have tried all of the following:

!r.Healthy.Equals("Healthy")
r.Healthy != "Healthy"
!(r.Healthy == "Healthy")
(r.Healthy == null | r.Healthy == "")  // the database shows it as NULL, but the datagrid just shows it as blank, so I figured I would cover both bases. 

What am I doing wrong?

Turns out there were two things happening.

First is I had manually added the Healthy property, and I had not set it to Nullable in the LINQ to SQL.dmbl. I found that out while debugging a different part of the program.

Second, no form of 'not equals' worked in a regular SQL query either, since the only two values for the Healthy property are Healthy and NULL. I guess NULL is not a value it can not be equal to. However, once I fixed the nullable issue in LINQ to SQL, the following worked:

 var reclist = from r in dbContext.Recipes where r.Name.Contains(srch) && r.Healthy == null select r;

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