簡體   English   中英

LINQ 到 SQL 不等於在 Select 語句中不起作用

[英]LINQ to SQL Not Equals not working in Select statement

我無法在 LINQ 到 SQL select 語句中使用“不等於”。

我有三個單選按鈕用於搜索 function 用於我的食譜程序,常規、健康和所有。 食譜有一個名為“健康”的字段,訪問它的唯一方法是通過程序,它唯一可以擁有的是 NULL 或健康。

搜索按鈕代碼如下。 Healthy and All 工作正常,但 rbRegRecipes 根本不顯示任何食譜。

這不是連接,所有字段都來自配方表。

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;
                }
            }
        }

我已經嘗試了以下所有方法:

!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. 

我究竟做錯了什么?

原來發生了兩件事。

首先是我手動添加了 Healthy 屬性,並且我沒有在 LINQ 到 SQL.dmbl 中將其設置為 Nullable。 我在調試程序的不同部分時發現了這一點。

其次,在常規的 SQL 查詢中也沒有任何形式的“不等於”,因為 Healthy 屬性的唯一兩個值是 Healthy 和 NULL。 我猜 NULL 不是它不能等於的值。 但是,一旦我修復了 LINQ 到 SQL 中的可空問題,以下工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM