سؤال

I'm currently working on a project where I'm going to do a lot of comparison of similar non-database (service layer objects for this discuss) objects and objects retrieved from the database via LinqToSql. For the sake of this discussion, assume I have a service layer Product object with a string field that is represented in the database. However, in the database, there is also a primary key Id that is not represented in the service layer.

Accordingly (as I often do for unit testing etc), I overrode Equals(Object), Equals(Product), and GetHashCode and implemented IEquatable with the expectation that I would be able to write code like this:

myContext.Products.Where(p => p.Equals(passedInProduct).SingleOrDefault();

And so forth.

The Equals override is tested and works. The objects are mutable so the usual caveats apply to the GetHashCode override. However, for the purposes of this example, the objects are not modified except by LtS and could be made readonly.

Here's the simple test:

  • Create a test object in memory and commit to the LtS context. By committing, the test object is populated with a few auto-generated fields.
  • Create another identical test object in memory (separate reference)
  • Attempt to retrieve the first object from the database using the second object as the criteria. (see code line above).

        // Setup
        string productDesc = "12A";
        Product testProduct1 = _CreateTestProductInDatabase(productDesc);
        Product testProduct2 = _CreateTestProduct(productDesc);
    
        // check setup
        Product retrievedProduct1 = ProductRepo.Retrieve(testProduct1);
        //Assert.IsNotNull(retrievedProduct1);
    
        // execute - try to retrieve the 'equivalent' product object
        Product retrievedProduct2 = ProductRepo.Retrieve(testProduct2);
    

A simplified version of Retrieve (cruft removed is just parameter checks etc):

using (var dbContext = new ProductDataContext()) {
    Product retrievedProduct = dbContext.Products
         .Where(p => p.Equals(product)).SingleOrDefault();

NB: The overridden Equals method knows not to care about the auto-generated fields from the database and only looks at the string that is represented in the service layer.

Here's what I observed: Retrieve on testProduct1 succeeds (no surprise, equal by reference) Retrieve on testProduct2 fails (null) The overridden Equals method called in the Retrieve method is never hit during either Retrieve calls However, the overridden Equals method is called multiple times by the context on SubmitChanges (called when creating the first test object in the database) (works as expected).

Statically, the compiler knows that the type of the objects being emitted and is able to resolve the type.

So my specific questions:

  • Am I trying to do something ill-advised? Seems like a straightforward use of Equals.
  • Corollary to first question: alternate suggestions to deal with linq to sql equality checking while keeping comparison details inside the objects rather than the repository
  • Why might I have observed the Equals method being resolved in SubmitChanges but not in the Where clause?
  • I'm as much interested in understanding as making my Equals calls work. But I also would love to learn how to make this 'pattern' work rather than just understand why it appears to be an 'anti-pattern' in the contest of LtS and C#.

Please don't suggest I just filter directly on the context with Where statements. Obviously, I can remove the Equals call and do that. However, some of the other objects (not presented here) are large and a bit complicated. For the sake of maintenance and clarity, I want to keep knowledge of how to compare itself to another of its own type in one place and ideally as part of the object in question.

Some other things I tried that didn't change the behavior:

  • Overloaded and used == instead
  • Casting the lambda variable to the type p => (Product)p
  • Getting an IQueryable object first and calling Equals in the Where clause

Some other things I tried that didn't work:

  • Creating a static ProductEquals(Product first, Product second) method: System.NotSupportedException:has no supported translation to SQL.

Thanks StackOverflow contributors!

Re Possible dups: I've read ~10 other questions. I'd love a pointer to an exact duplicate but most don't seem to directly address what seems to be an oddity of LinqToSql.

هل كانت مفيدة؟

المحلول

Am I trying to do something ill-advised?

Absolutely. Consider what LINQ to SQL does: it creates a SQL representation of your query. It doesn't know what your overridden Equals method does, so can't translate that logic into SQL.

Corollary to first question: alternate suggestions to deal with linq to sql equality checking while keeping comparison details inside the objects rather than the repository

You'd need to do something with expression trees to represent the equality that way - and then build those expression trees up into a full query. It won't be fun, but it should be possible. It will affect how you build all your queries though.

I would have expected most database representations to be ID-based though, so you should be able to just compare IDs for equality. Usually when I've seen attempts to really model data in an OO fashion but store it in a database, the leakiness of the abstraction has caused a lot of pain.

Why might I have observed the Equals method being resolved in SubmitChanges but not in the Where clause?

Presumably SubmitChanges is working against a set of in-memory objects to work out what's changed - it doesn't have to do any conversion to SQL to do that part.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top