4

It seams simple but I really don't get it.I am using linq and Entity Framework to retrieve an object from Database by a simple query like this

loggedinUser = (from user in context.Users
                 where user == _guid
                 select user).ToList()[0];

I know that I can use .FirstOrDefault(), but I don't think that my problem has something to do with the way I get my user.

After getting user If I check it with this condition

if (loggedinUser != null)
   {
     ToLocation = String.Format("{0} {1} {2} {3}", loggedinUser.StreetAddress,loggedinUser.City, loggedinUser.Province, loggedinUser.PostalCode);
   }

it doesn't work, as if it is null, but it's not.when I use this condition it works.

if (loggedinUser == null)
{ }
else
{
  ToLocation = String.Format("{0} {1} {2} {3}", loggedinUser.StreetAddress,loggedinUser.City, loggedinUser.Province, loggedinUser.PostalCode);
}

I always use this type of condition (Obj != null) and it works,the answer should be simple, but I don't really get why it doesn't this time. Am I missing something?

The only point is that the class for this entity is located in another project.Can it be the problem?

The project which this class is located in is in VB.Net :

<Table("Users")>
Public Class User
<Key()>
Public Property UserID As Integer

Public Property Username As String
Public Property PasswordEncrypted As String
Public Property LastLogin As DateTime 
Public Property CreatedByUserID As Integer
Public Property DateCreated As DateTime
Public Property Deleted As Boolean '?
Public Property Email As String
Public Property StreetAddress As String
Public Property City As String
Public Property Province As String
Public Property PostalCode As String

<NotMapped()>
Public Property Lat As Double

<NotMapped()>
Public Property Lon As Double

Public Property GUID As String

<NotMapped()>
Public Property EULAAgreed As DateTime

Public Overrides Function ToString() As String
    Return Username
End Function

Public Overrides Function Equals(ByVal obj As Object) As Boolean
    If (obj Is System.DBNull.Value) Then
        Return MyBase.Equals(obj)
    ElseIf (TypeOf obj Is String) Then
        Return MyBase.Equals(obj)
    Else
        Try
            Return UserID = CType(obj, Entities.User).UserID
        Catch ex As Exception
            Return UserID
        End Try
    End If
End Function

End Class

Maryam Arshi
  • 1,974
  • 1
  • 19
  • 33
  • 5
    There's something else going on. Can we see the actual null check? – Ed S. Jan 22 '14 at 18:32
  • In the first case, is it a multiline statement? If so, is it wrapped in `{ .. }`? If not, only the first line after the `if` gets the `if` applied. – Magus Jan 22 '14 at 18:33
  • I changed it to have my complete code. – Maryam Arshi Jan 22 '14 at 18:39
  • Can you set a breakpoint here `if (loggedinUser != null)` and check what the actual value of `loggedinUser` is? – David Jan 22 '14 at 18:44
  • The problem is that in my workplace we do not have debug environment and we should build our program, install it on server and see the result, that's why I can not debug it.and @rae1 yes they are the same, I edited my post. – Maryam Arshi Jan 22 '14 at 18:48
  • 1
    You should try @Pheonixblade9 then and see if it corrects the issue. Furthermore, if you cannot debug, I would advise you place some trace messages to the Windows Event Log displaying the type of `loggedinUser` for example, `EventLog.Write("Instance of type: " + loggedinUser.GetType().FullName)`. It is a way to debug without a debugger. – rae1 Jan 22 '14 at 18:51
  • Have for some reason overridden the `==` operator for the `Entities.User` type? – rae1 Jan 22 '14 at 19:03
  • @rae1 No, I've thought of that myself and checked the entity class, it is not, let me put the whole class into the question. – Maryam Arshi Jan 22 '14 at 19:08
  • Have you tried changing the array index to using `.First()` instead? – Codeman Jan 22 '14 at 21:02

3 Answers3

4

It's because LINQ-SQL/EF don't give you null. They give you DBNull.

Change your comparison to this:

if (loggedinUser != DBNull.Value)
Codeman
  • 12,157
  • 10
  • 53
  • 91
  • 1
    what do you mean by LINQ don't give you null? ofcourse it gives you null,if it's true how is that second if statement working ? – Selman Genç Jan 22 '14 at 18:35
  • @Selman22 [What is the difference between null and System.DBNull.Value?](http://stackoverflow.com/a/4958408/1992193) – Brock Hensley Jan 22 '14 at 18:37
  • @MaryamArshi What other parts of the code? You need to update the question with *actual* code, otherwise, it is hard to tell what's going on. – rae1 Jan 22 '14 at 18:38
  • @rae1 I mean in other classes , or even in this class for other objects. – Maryam Arshi Jan 22 '14 at 18:40
  • And by the way it throw error :` Error 15 Operator '!=' cannot be applied to operands of type 'Entities.User' and 'System.DBNull'` – Maryam Arshi Jan 22 '14 at 18:46
  • 1
    EF doesn't give you nulls? I don't think so. And the comparison provided would never work. How did this get upvotes? – jamesSampica Jan 22 '14 at 19:25
2

It's possible that you have code like this:

if (loggedinUser != null)
    doSomething();
    doSomethingElse();

The problem is that the if's scope ends with the first statement. Include braces if you have multiple statements.

if (loggedinUser != null)
{
    doSomething();
    doSomethingElse();
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

Although you got the answer for your question. but still these answers also worth a read.

Well, null is not an instance of any type. Rather, it is an invalid reference.

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*We would normally say null, but I don't want to confound the issue.

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

Original Source

and a very good explanation by Marc in What is the point of DBNull?

Community
  • 1
  • 1
JSJ
  • 5,653
  • 3
  • 25
  • 32