Posts Tagged ‘Cannot compare entities associated with different tables.’

Linq to SQL Query gives an InvalidOperationException with message “Cannot compare entities associated with different tables.”

Wednesday, September 15th, 2010

If you try to do a Linq to SQL query and it runs fine, but gives you an exception of type InvalidOperationException and the message is “Cannot compare entities associated with different tables.” then it probably means that you are trying to pass in an object of one type and compare it to another type.  I suspect that you will probably only get this error if Linq attempts to translate the error to SQL – if you run it in memory, you might not get an error at all, as it may just do a straight object comparison and conclude that they are different objects.

An example would be something like

Dim p = DBContext.People.First
Dim q = From a in DBContext.Addresses Where a Is p
Dim addr = q.First

The final line will result in this exception as Linq to SQL is attempting to translate the query into SQL and it (correctly) can’t find any way of writing a query that compares a person to an address!