Using Equals

In some cases you can't use QBE as a retrieval method. In these cases you must override the object's equals method to allow you to compare objects data. For example:

Pilot.cs: Equals
1public override bool Equals(object obj) 2 { 3 Pilot pilot = (Pilot)obj; 4 return pilot.Name.Equals(_name) && pilot.Points == _points; 5 }
Pilot.vb: Equals
1Public Overloads Overrides Function Equals(ByVal obj As Object) As Boolean 2 Dim pilot As Pilot = DirectCast(obj, Pilot) 3 Return pilot.Name.Equals(_name) AndAlso pilot.Points = _points 4 End Function

Note, that you must implement hashCode/GetHashCode method, when you implement equals:

Pilot.cs: GetHashCode
1public override int GetHashCode() 2 { 3 return _name.GetHashCode() ^ _points.GetHashCode(); 4 }
Pilot.vb: GetHashCode
1Public Overloads Overrides Function GetHashCode() As Integer 2 Return _name.GetHashCode() Xor _points.GetHashCode() 3 End Function

Now we can use the equals method to compare an object from the database to an object prototype:

EqualityExample.cs: testEquality
01private static void TestEquality() { 02 IObjectContainer container = Database(); 03 if (container != null) { 04 try { 05 IList<Pilot> result = container.Query<Pilot>(delegate(Pilot p){ 06 return p.Name.Equals("Kimi Raikkonnen") && 07 p.Points == 100; 08 }); 09 Pilot obj = result[0]; 10 Pilot pilot = new Pilot("Kimi Raikkonnen", 100); 11 string equality = obj.Equals(pilot) ? "equal" : "not equal"; 12 System.Console.WriteLine("Pilots are " + equality); 13 } catch (Exception ex) { 14 System.Console.WriteLine("System Exception: " + ex.Message); 15 } finally { 16 CloseDatabase(); 17 } 18 } 19 }
EqualityExample.vb: testEquality
01Private Shared Sub TestEquality() 02 Dim container As IObjectContainer = Database() 03 If container IsNot Nothing Then 04 Try 05 Dim result As IList(Of Pilot) = container.Query(Of Pilot)(AddressOf PilotTestMatch) 06 Dim obj As Pilot = result(0) 07 Dim pilot As New Pilot("Kimi Raikkonnen", 100) 08 Dim equality As String = IIf(obj.Equals(pilot), "equal", "not equal").ToString 09 System.Console.WriteLine("Pilots are " + equality) 10 Catch ex As Exception 11 System.Console.WriteLine("System Exception: " + ex.Message) 12 Finally 13 CloseDatabase() 14 End Try 15 End If 16 End Sub