Entity Framework and RIA Services do not allow Entities to be added/removed from cross containers. In order to move Entity from one DomainContext/ObjectContext to another DomainContext/ObjectContext, we need to recursively detach the object graph and attach it to other DomainContext/ObjectContext.
Object Graph
Single entity can be easily detached and attached from EntitySet where it belongs, but the problem comes when navigation properties of entity are not empty. Entity object along with navigation properties is called Object Graph because if you notice, navigation property’s navigation property will contain reference to same entity and that will result in endless recursive code for Detach/Attach.
An entity with the same identity already exists in the EntitySet
When you try to detach entity from old DomainContext/ObjectContext and attach it to DomainContext/ObjectContext, it may give you an error that entity with same identity already exists and it will throw an exception. In this case we will just simply reuse the existing entity instead of attaching the entity we have.
Entity cannot be attached to this EntityContainer because it is already attached to another EntityContainer
In case of ObjectGraph, your root level entity is already detached, but navigation properties are not detached, and while you try to attach your root level entity, it will throw same error for entities that exist in navigation properties. Because detach method does not recursively detach every entity from navigation properties.
Attach/Detach Extension Methods
Finally after brainstorming little, I made following class that will allow you to recursively detach/attach object graphs from DomainContext. You can replace DomainContext to ObjectContext to use it inside Entity Framework.
- /// <summary>
- /// DomainContext Extensions
- /// </summary>
- public static class DomainContextExtensions {
- /// <summary>
- /// Recursively Attaches entity loaded from Other DomainContext to
- /// current specified DomainContext
- /// </summary>
- /// <param name="context">DomainContext where entity will be attached</param>
- /// <param name="entity">Entity loaded from other DomainContext</param>
- /// <returns></returns>
- public static Entity Attach(this DomainContext context, Entity entity)
- {
- if (entity == null || entity.EntityState != EntityState.Detached)
- return entity;
- Entity newEntity = entity;
- Entity[] list = new Entity[] { entity };
- foreach (Entity c in context.EntityContainer.LoadEntities(list,
- LoadBehavior.MergeIntoCurrent))
- {
- newEntity = c;
- break;
- }
- // recursively attach all entities..
- Type entityType = typeof(Entity);
- // get all navigation properties…
- Type type = entity.GetType();
- foreach (var item in type.GetProperties())
- {
- if (entityType.IsAssignableFrom(item.PropertyType))
- {
- Entity navEntity = Attach(context, item.GetValue(entity, null)
- as Entity);
- item.SetValue(newEntity,navEntity, null);
- continue;
- }
- if (item.PropertyType.Name.StartsWith("EntityCollection"))
- {
- IEnumerable coll = item.GetValue(entity, null) as IEnumerable;
- List<Entity> newList = new List<Entity>();
- foreach (Entity child in coll)
- {
- newList.Add(Attach(context, child));
- }
- dynamic dcoll = item.GetValue(newEntity,null);
- foreach (dynamic child in newList)
- {
- dcoll.Add(child);
- }
- }
- }
- return newEntity;
- }
- /// <summary>
- /// Recursively detaches entities from DomainContext, this
- /// method detaches every navigation properties
- /// of current Entity as well.
- /// </summary>
- /// <param name="context"></param>
- /// <param name="entity"></param>
- public static void Detach(this DomainContext context, Entity entity)
- {
- if (entity == null || entity.EntityState == EntityState.Detached)
- return;
- EntitySet nes = context.EntityContainer.GetEntitySet(entity.GetType());
- nes.Detach(entity);
- Type entityType = typeof(Entity);
- // get all navigation properties…
- Type type = entity.GetType();
- foreach (var item in type.GetProperties())
- {
- if (entityType.IsAssignableFrom(item.PropertyType))
- {
- Detach(context,item.GetValue(entity, null) as Entity);
- continue;
- }
- if (item.PropertyType.Name.StartsWith("EntityCollection"))
- {
- IEnumerable coll = item.GetValue(entity, null) as IEnumerable;
- foreach (Entity child in coll)
- {
- Detach(context,child);
- }
- }
- }
- }
- }