riteshrao / ncommon

A framework for implementing commonly used design patterns when using Domain Driven Design
www.codeinsanity.com
218 stars 61 forks source link

Problem with saving attached Entity with Entity Framework #20

Open Assassyn opened 13 years ago

Assassyn commented 13 years ago

When you load entity, commit the unit of work, after the change attempt on such entity there is no way to attach(reattach) it to context and submit changes to database. I have problem when I was using IEntityWithKey but I suppose that similar problem can happens for POCO type of entities.

Problem could be resolved by adding: public void Attach(T entity) where T : class { //If the entity implementes the IEntityWithKey interface then we should use Context's Attach metho //instead of the set's Attach. Getting an exception //"Mapping and metadata information could not be found for EntityType 'System.Data.Objects.DataClasses.IEntityWithKey" //when using set's Attach. var entityWithKey = typeof (IEntityWithKey); if (entityWithKey.IsAssignableFrom(entity.GetType())) { _context.Attach((IEntityWithKey)entity); // new line seem to solve the problem _context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); return; }

        GetObjectSet<T>().Attach(entity);
        //_context.DetectChanges(); //Required for POCO entities
    }