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
It's because LINQ-SQL/EF don't give you null. They give you DBNull.
Change your comparison to this:
if (loggedinUser != DBNull.Value)
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With