Posts Tagged ‘Linq to SQL’

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!

Finding a table in a Linq to SQL DBML file in Visual Studio 2008

Monday, March 1st, 2010

One problem that can take up a lot of time if you are working in a large project with a lot of tables in the DBML database model file when using Linq to SQL in Visual Studio is finding the table in the diagram.  Control+F doesn’t work, and it can be a real pain to scroll around for ages.  However, the following article mentions a very simple solution – just use the dropdown at the top of the properties window!  Seems obvious, but I know quite a few people have been complaining about that for months!

Taken from Is there a way to find a table in a DBML file in Visual Studio 2008? – Stack Overflow.

Linq to SQL Quirks Part 4: Circular References

Friday, July 10th, 2009
This entry is part of a series, Linq to SQL Quirks»

In a project that I am working on at the moment, I have a situation where I have a Person table and a Family table.  The Person table has a FamilyID field, which is a foreign key to the Families ID (primary key) field, and the Family table has a DefaultPersonID, which is another foreign key back to Person to store the default contact for a family.

The problem is that if I create a new Person and Family with the Person being the DefaultContact, I get an InvalidOperationException thrown with a message “A cycle was detected in the set of changes”.  The problem is that Linq to SQL doesn’t know what to store first.  The only way that I have come up with to get around this is to do the following…

            If Person.ID = 0 AndAlso Not Person.Family Is Nothing Then
               
                Dim fam = Person.Family
                Person.Family = Nothing

                DBContext.SubmitChanges()
                Person.Family = fam

            End If

            DBContext.SubmitChanges()

This works by breaking the circular reference, so that there is only a 1 way reference, then submitting to the database, and once submitted, restoring the removed reference and submitting changes again

Linq to SQL Quirks Part 3 – Extension to Get Around the Delete Problem

Tuesday, June 30th, 2009
This entry is part of a series, Linq to SQL Quirks»

My previous post about problems deleting can be partly handled with an extension method to the Linq to SQL Table(Of T) class with something like this…

         Public Sub DeleteOnSubmitOrDetach(Of T As Class)(ByVal table As System.Data.Linq.Table(Of T), ByVal o As T)
            Dim IDProperty = o.GetType.GetProperty("ID")
            If IDProperty Is Nothing Then
                Throw New System.MissingFieldException("Trying to delete object of type " & GetType(T).Name & " - does not have an ID field")
            End If
            If IDProperty.GetValue(o, New Object() {}) = 0 Then
                table.InsertOnSubmit(o)
            End If
            table.DeleteOnSubmit(o)
        End Sub

Note that you’ll need to import System.ComponentModel and System.Reflection and possibly some others, and it assumes that you have an IDENTITY ID field by that name on all of your classes that you use this with.

Linq to SQL Quirks Part 2: DeleteOnSubmit and Entity not Attached

Tuesday, June 23rd, 2009
This entry is part of a series, Linq to SQL Quirks»

If you use an implicit insert on a new object and then decide that you don’t actually want it, you have a bit of a problem.  First of all, you need to remove the relationships that you created so that it doesn’t show up in any places that it shouldn’t.  The problem with this is that Linq will still kind of (see below) have it marked for insertion, so if you call SubmitChanges without doing anything else, it will either still insert it, or if you’ve removed a relationship which relies on a non-nullable foreign key, you’ll get an error like

“An attempt was made to remove a relationship between a A and a B. However, one of the relationship’s foreign keys (A.BID) cannot be set to null.”

Where A and B are the 2 appropriate Linq to SQL classes.

The next thing we need to do then is to make sure that Linq to SQL removes the item from the insert list.  The only way that I have found to do this is to call DeleteOnSubmit on the appropriate table.  The problem is that if we do that at this point, we get an InvalidOperationException with message “Cannot remove an entity that has not been attached.”

Apparently, Linq to SQL knows it is supposed to insert it, but it isn’t properly attached.  To get around this, we need to call InsertOnSubmit on the appropriate table before calling DeleteOnSubmit.

That’s all fine and dandy and works, as long as you are trying to delete something that hasn’t been inserted yet.  Normally, however, I use the same code whether it has been inserted or not, and of course if you call InsertOnSubmit on an entity that has already been inserted, you get an InvalidOperationException saying “Cannot add an entity that already exists.”.  Therefore, before you call InsertOnSubmit, you need to check if it actually has already been inserted.  Since I always have identity fields with the name ID on all my tables and Linq to SQL updates these when it does an insert, I normally just check that the ID is 0 before inserting.

The resulting steps that you need to solve the problem are therefore: –

  1. Remove the relationships from item
  2. If the ID=0 then DataContext.Table.InsertOnSubmit(item)
  3. DataContext.Table.DeleteOnSubmit(item)

You shouldn’t actually have to call DataContext.SubmitChanges at this point – the whole point in the exercise is to mean it will be safe when you do later.

Alternatively, you can just throw away the datacontext without calling SubmitChanges, but I find that is rarely an option because there may be other data that needs submitting.

By the way, you need to do the first step of removing the relationships in order to make sure that none of your code accidentally tries to access the removed object as it will still be in memory as a related object until SubmitChanges is called otherwise and you could end up processing it when accessing entities related to an object that it is related to.

Linq to SQL Quirks Part 1: Implicit Inserts

Tuesday, June 23rd, 2009
This entry is part of a series, Linq to SQL Quirks»

There are a few things that Linq to SQL can be a bit funny about that aren’t so obvious.

First of all, there are what I call implicit inserts.  You might not have realised that you don’t actually need to explicitly call InsertOnSubmit on a table for Linq to SQL to do the insert as long as you have created a relationship to an object which already exists in the database.  Linq to SQL will automatically insert the new object on the next SubmitChanges call.