Reputation: 432
I'm currently using Linq to Sql (dbml) for one of my projects. (c# win forms)
I've created partial and metadata classes, and also implemented Equals() and == based on these Guidelines
the problem I'm having is when I try to use these equals operations within a linq query.
Entities.MyClass.Where(p => p.Equals(myClassObject));
I've also attempted the following
Entities.MyClass.Where(p => Object.Equals(p, myClassObject));
Entities.MyClass.Where(p => p == myClassObject);
What's the best way to implement this?
Instead of attempting to override Equals I'm currently doing the following (but I'm checking 8 values, so it just seems cumbersome) :
Entities.MyClass.Where(p => p.value1 == myClassObject.value1 && p.value2 == myClassObject.value2 ......)
Upvotes: 0
Views: 3169
Reputation: 469
You must create an Expression<Func<M,V>>
object to pass to the where clause. You could put the answer to this question in a method and create it that way.
Upvotes: 0
Reputation: 13161
LINQ to SQL (or any other LINQ provider that translates your LINQ expressions into provider queries for that matter), doesn't have knowledge of how you've overriden Equals
.
Consequently, when you use your Equals
method in a LINQ query, the provider doesn't know that it should compare using your 8 properties.
You could pre-process your LINQ query, before it's handled by the LINQ provider, by traversing the expression tree and expanding calls to your Equals
method into the corresponding 8 property comparison. This way, the LINQ provider gets an expression for your implementation. If the equals implementation changes, you only have to change it in two places (the Equals
override and the corresponding substitution expression).
Upvotes: 3