Entity Framework对象不为null,但`== null`返回true

时间:2014-06-23 16:43:20

标签: c# entity-framework

我的代码:

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

这正确地返回了我可以在visual studio中的intellisense中查看的对象是正确的。

下一行是:

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方法中。太奇怪了。

编辑:这是此部分的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();
}

1 个答案:

答案 0 :(得分:5)

如果您添加了自定义==运算符重载并使其变得混乱,则会发生这种情况。重载会更喜欢==(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);
    }
}