c# - Entity Framework 对象不为 null 但 `== null` 返回 true

标签 c# entity-framework

我的代码:

var x = myEntities.MyTable
                  .Include("MyOtherTable")
                  .Include("MyOtherTable.YetAnotherTable")
                  .SingleOrDefault(c => c.Name == someName);

这会正确返回我可以在 visual studio 中的智能感知中查看为正确的对象。

下一行是:

if (x == null)
{
}

但是,此语句返回 true 并且 {} 中的代码执行。什么可能导致这种情况?

编辑:

在空检查上方添加了这一行:

var someName = x.Name;

此代码完美运行,someName 成为一个 string,其中包含对象的名称。

== null 仍然返回 true。

IDE 截图:

enter image description here

enter image description here

编辑:函数中的代码似乎可以工作:

    public void bibble(MyObjectType s)
    {
        if (s == null)
        {

            throw new Exception();
        }
    }
--
    string someName = testVariable.Name;

    this.bibble(testVariable); // Works without exception

    if (testVariable == null)
    {
        // Still throws an exception
        throw new Exception();
    }

现在它不会在另一个方法中评估为 true,但在同一变量的 main 方法中评估为 true。太奇怪了。

编辑:这是本节的 IL:

  IL_0037:  callvirt   instance string [MyLibrary]MyLibrary.MyCompany.MyObjectType::get_Name()
  IL_003c:  stloc.3
  IL_003d:  ldarg.0
  IL_003e:  ldloc.2
  IL_003f:  call       instance void MyOtherLibrary.ThisClass::bibble(class [MyLibrary]MyLibrary.MyCompany.MyObjectType)
  IL_0044:  nop
  IL_0045:  ldloc.2
  IL_0046:  ldnull
  IL_0047:  ceq
  IL_0049:  ldc.i4.0
  IL_004a:  ceq
  IL_004c:  stloc.s    CS$4$0001
  IL_004e:  ldloc.s    CS$4$0001
  IL_0050:  brtrue.s   IL_0059
  IL_0052:  nop
  IL_0053:  newobj     instance void [mscorlib]System.Exception::.ctor()
  IL_0058:  throw

编辑:更奇怪的是:

var myEFObjectIsNull = testVariable == null;

// Intellisense shows this value as being FALSE.

if (myEFObjectIsNull)
{
    // This code is ran. What.
    throw FaultManager.GetFault();
}

最佳答案

如果您添加了自定义 == 运算符重载并弄得一团糟,就会发生这种情况。重载将更喜欢 ==(MyTable,MyTable) 重载,并且在与 null 比较时会选择它:

static class Program {
    static void Main() {
        Foo x = new Foo();
        if(x==null) {
            System.Console.WriteLine("Eek");
        }
    }
}

public class Foo {
    public static bool operator ==(Foo x,Foo y) {
        return true; // or something more subtle...
    }

    public static bool operator !=(Foo x, Foo y) {
        return !(x==y);
    }
}

关于c# - Entity Framework 对象不为 null 但 `== null` 返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24371096/

相关文章:

c# - 加里奥.Model.ModelException : An exception occurred while invoking a test driver

C#:没有完全扩展环境变量?

c# - 如何初始化一个接口(interface)?

c# - EF 生成的类和模型之间的关系?

c# - 如何在 Entity Framework 和 EF Core 中使用 .Include()

c# - 绑定(bind)到集合的 View 并在 WPF 中调用 ToString()

c# - Unity、场景和 ScriptableObject

c# - 有没有办法使属性成为 Required 但仅适用于前端而不适用于数据库?

c# - Entity Framework 6 : Adding child object to parent's list vs. 将子项的导航属性设置为父项

.net - Entity Framework - 已添加具有相同键的项目。 - 尝试定义外键关系时出错