LinQ2SQL Entity Generic Detach

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
Posts: 1
Joined: Thu 29 Jul 2010 13:51

LinQ2SQL Entity Generic Detach

Post by Alberto7DA » Thu 29 Jul 2010 14:40

Hello to everyone.

Here is the briefing:
The main goal is to do something like this:


And the entity will attach nicely to current DataContext whenever was attached or not to previous DataContext.

Here is the causes:
I have been working with LinQ2SQL with an N-Tier application. Of course i
work with disconnected DataContext and for each user event i created a
new DataContext for gather Entities instances and perhaps to modify

The entities instances gathered in one user event are used by
other tiers (in fact these entities are used like transfers objects); so
in next events i need the previous gathered entities; but (and it is my problem) the entities used in one DataContext remain attached to the DataContext so i can't use the previous gathered entities in new DataContex.

In my first solution I create a new entity and copy all data from the old
entity and then attach the new entity at new DataContext but it is also a
mistake because the dependency graph remain attached to old DataContext.

An other solution (not good) is disable the DeferingLoading at all; I
don't like that. It lose all advantage of ORM.

I learn in google that if you reset the relations between entities then
the entity detach from DataContext.

So I improve something more sophisticated but I think is dense (but very productive) and also i don't know if will work for every situation. I want that someone tell me if this is fine and if it's practical. Or another way to do that.

The idea is to detach any entity and related entities graph generic whit help of reflexion and remain all data and entity graph intact.

The strategy for each entity is:
Find all properties that return an entity (Is easy because all entities
belong to specific namespace) this are parent entities

if parent entity is not null set this property to null and detach parent
entity recursively. After that restore the parent entity.

Find all properties that return an EntitySet (The child entities)
if the set is LoadedOrAssignedValues the proced to detach childs:
Save a copy of list of entities
Clear the entity Set
Detach each child entity recursively.
Restore the entity set.

Of course I check the entities so no detach entities twice.

Thanks in advance.

Devart Team
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Post by AndreyR » Mon 02 Aug 2010 10:41

The approach you are using seems to be correct, there should be no problems with it.
Thank you for sharing your knowledge.

Post Reply