Question

I need to find out if an object with a particular primary key is already attached to a DataContext and get the entity from the DataContext if it is attached. Is there any way at all to do this that doesn't require Reflection with full trust?

Ideally, I would like to call GetCachedObject(), but I'd have to use reflection to get at that, and I'm pretty sure I'd have to be in full trust mode, which won't work in a hosted environment.

I'm open to thinking outside the box here. Also, I can fully control the generated LinqToSql code, so that's not a problem either. I can rewrite my DataContext class. Is there any way to get access to the IdentityManager, replace the IdentityManager with my own abstraction, etc? Any and all ideas are welcome.

Was it helpful?

Solution

One potential 'workaround'. I haven't tried it, so don't know if it will work... ...but since you said 'out of the box': Assign a bad connection or bad connection string to the DC, or mess up the sqlconnection it already has. Next query for the object by PK. If it is in the cache, there's a good chance that L2S won't notice that the connection is bad, so you should get the object back. If it is not in the cache, L2S should try a db roundtrip and you'll get an exception.

As I said, dirty and untested, but worth trying if you really want to avoid using reflection to get access to the identity manager / change tracker. Not sure if it will save you any CPU cycles though... :)

OTHER TIPS

If you control the generated code, why not let the ctor of every entity register itself in a per-thread dictionary. That way you have all existing entities of the current thread. If you have one datacontext per thread, you now have a list of all loaded (but not necessarily attached) entities.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top