Consider the following:
I have a high level component that deals with detached Linq to Sql entities. We'll call them Foo and Prop, where a single Foo may be associated with many Prop, but every Prop is always associated with exactly one Foo. So:
+------+ 1 0..n +------+
| Foo |-----------| Prop |
+------+ +------+
Very simple, I hope you agree.
At a high level of abstraction in my application, it's important to me to be able to display Foo's, so I keep a cache of them, all nicely detached from their source DataContext via a serialize/deserialize method. It seems to work sufficiently well.
Now, a user may come along and choose to add or modify a Prop on a Foo. I attempt to Prop Save(Prop data) the new Prop. Initially I did so naively:
db.Prop.InsertOnSubmit(data);
db.SubmitChanges();
but this resulted in many duplicate Foo's being added to the database. The apparent solution was to attach the offending Foo to the new DataContext before insertion:
db.Foo.Attach(data.Foo); // Avoid duplicate records
db.TaskDuration.InsertOnSubmit(data);
db.SubmitChanges();
This seemed to work in the short term, but then I discovered that trying to add a second Prop to a Foo would result in a NotSupportedException.
So I find myself in a quandary. On the one hand, I must attach the Prop's Foo to the DataContext because I must avoid ridiculously duplicated records. But on the other hand, if I do, I munge the caller's Foo cache by attaching a Foo when the caller expects them to remain unattached, thus exploding a little later on. I can't detach in the callee because the callee can't change the caller's cached Foo, and an entity can't be detached once it's been attached anyway.
Am I doing something fundamentally wrong by using detached entities in a cache? Is there some better design for a detached scenario with Linq to Sql? Or do I need to start considering alternative technologies?