Hi, I've got an application where I'm implementing a singleton pattern in the database, and I'm running into huge problems.
I've got the following Table, SingletonTable
+-------------+-------+------------+
| Column Name | Type | Allow Null |
+-------------+-------+------------+
| Id | Int | No |
| VarType | Int | No |
| TypeARef | Int | Yes |
| TypeBRef | Int | Yes |
+-------------+-------+------------+
In the EF, this is broken down into two concrete types, TypeA and TypeB. TypeARef is on TypeA, TypeBRef is on TypeB, and VarType is the discriminator. There is a unique index on (VariableType, TypeARef, TypeBRef). The idea of the singleton pattern is that we only ever have 1 row in the database for a given value tuple, so whenever we add a reference to to SingletonTable, we first check to see if that row exists, if it does, we return the row in the DB, if it doesn't, we create the row and return a reference to the newly created row. I've abstracted this out into a method, GetSingleton.
The problem is whenever I use the method GetSingleton, I get the follwoing Exception:
Test method UnitTests.CreateBasicData.CreateFTIData threw exception: System.InvalidOperationException: The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object
I'm using it as such
var newRow = new SomeType
{
singletonValue = GetSingleton(new TypeB{ TypeBRef = Foo })
}
The problem appears to be that I can't add a reference from something not already in the data context to something that is in the data context. Is this right? How do I work around this limitation?
Thanks, Roy