Ondrej Petrzilka
Ondrej Petrzilka

Reputation: 1579

Entity framework, compare complex types

How do I compare complex types in queries?

Does not work (always returns null, EDIT: since new version of EF it throws exception):
DbVector3 pos = new DbVector3() { X = 0, Y = 0, Z = 0};
db.PhysObjects.FirstOrDefault(s => s.Position == pos);

Works:
DbVector3 pos = new DbVector3() { X = 0, Y = 0, Z = 0};
db.PhysObjects.FirstOrDefault(s => s.Position.X == pos.X && s.Position.Y == pos.Y && s.Position.Z == pos.Z);

Is there any way to make first example working?

EDIT: Sorry, I probably mention only in title that this is entity framework.

db is ObjectContext, PhysObjects is ObjectSet<>

Upvotes: 1

Views: 1285

Answers (2)

Ondrej Petrzilka
Ondrej Petrzilka

Reputation: 1579

No, it's not supported, unless both values are in database.

Upvotes: 2

Lloyd Powell
Lloyd Powell

Reputation: 18810

You need to override the Equals function in your DbVector class, so that when comparisons are made it will be used to compare 2 objects.

protected override bool Equals(object comparer)
{
    DbVector3 compareObj = obj as DbVector3;

    return compareObj.X == this.X && compareObj.Y == this.Y && compareObj.Z == this.Z;
}

You can also do the same for the == and != operators. Something similar to below :

public static bool operator ==(DbVector3 a, DbVector3 b)
{
   return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
}

public static bool operator !=(DbVector3 a, DbVector3 b)
{
   return !(a == b);
}

Have a read of MSDN - Guidelines for Overriding for more information.

Upvotes: 3

Related Questions