c# - Entity Framework Where 子句奇怪的行为

标签 c# entity-framework

所以我正在使用 EF 并尝试进行非常简单的数据库调用。我对其他对象进行了相同的调用,但没有得到这种行为。行为是,如果我在我的 where 语句中链接两个子句,我将不再得到任何结果。下面是一些示例代码:

public List<Widgets> FindAll(long? relatedGadgetID)
using (myDBContext db = new myDBContext())
{
    return db.Widgets.Where(w => w.Deleted == false && w.GadgetID == relatedGadgetID).ToList();
    // This does not get any of the objects in the database
}

public List<Widgets> FindAll(long? relatedGadgetID)
using (myDBContext db = new myDBContext())
{
    return db.Widgets.Where(w => w.Deleted == false).Where(w => w.GadgetID == relatedGadgetID).ToList();
    // This does not get any of the objects in the database
}

public List<Widgets> FindAll(long? relatedGadgetID)
using (myDBContext db = new myDBContext())
{
    var x =  db.Widgets.Where(w => w.Deleted == false).ToList();
    return x.Where(w => w.GadgetID == relatedGadgetID).ToList();
    // This DOES!
}

为什么?

编辑:关闭评论,我尝试了解决方法,但仍然没有用。这是我尝试过的方法,我做错了什么吗?

public List<Widgets> FindAll(long? relatedGadgetID)
using (myDBContext db = new myDBContext())
{
    return db.Widgets.Where(w => w.Deleted == false && (relatedGadgetID == null ? w.GadgetID == null : w.GadgetID == relatedGadgetID)).ToList();
    // Still doesn't work =(
}

Edit2:尝试了另一个修复,仍然没有运气。

public List<Widgets> FindAll(long? relatedGadgetID)
using (myDBContext db = new myDBContext())
{
    return db.Widgets.Where(w => (w.Deleted == false) && (w.GadgetID == relatedGadgetID || (relatedGadgetID == null && w.GadgetID == null))).ToList();
    // Still doesn't work =(
}

Edit3:尝试了 Object.Equals,还是没有。

public List<Widgets> FindAll(long? relatedGadgetID)
using (myDBContext db = new myDBContext())
{
    return db.Widgets.Where(w => w.Deleted == false && w.GadgetID.Equals(relatedGadgetID)).ToList();
    // Still doesn't work =(
}

最佳答案

在我早期修复它的尝试中,我不小心将我的类属性更改为不可为空,而表列仍然是。一旦我意识到这一点,最初的尝试仍然有相同的结果,但解决方法有效。我最终使用了第一个编辑解决方法。谢谢碎玻璃!

关于c# - Entity Framework Where 子句奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130560/

相关文章:

c# - 在 asp.net 服务器端代码中?

c# - 有没有办法在序列化时自动初始化空子对象?

c# - 用于筛选和循环遍历多个表的 ASP.NET LINQ 查询

azure - "Login failed for user"在 Azure SQL 中为 "The underlying provider failed on Open"

sql - 使用SQLite的 Entity Framework

c# - 在一个 Linq to Entities 查询中多次实现 "like"运算符

c# - WMI:远程编辑注册表

c# - 使用计时器显示文本 3 秒?

mysql - Entity Framework 电动工具 Beta 4 与非 - 使用 MySql

c# - Linq Include 和 Where 父子关系条件