zzzprojects / GraphDiff

GraphDiff is a library that allows the automatic update of a detached graph using Entity Framework code first.
https://entityframework-graphdiff.net/overview
MIT License
333 stars 102 forks source link

More explicit error message on Merge method #93

Closed BenLewies closed 9 years ago

BenLewies commented 9 years ago

The following method within GraphDiffer.cs applies:

public T Merge(T updating, QueryMode queryMode = QueryMode.SingleQuery)
    {
        // todo query mode
        bool isAutoDetectEnabled = _dbContext.Configuration.AutoDetectChangesEnabled;
        try
        {
            // performance improvement for large graphs
            _dbContext.Configuration.AutoDetectChangesEnabled = false;

            // Get our entity with all includes needed, or add a new entity
            var includeStrings = _root.GetIncludeStrings(_entityManager);
            T persisted = _queryLoader.LoadEntity(updating, includeStrings, queryMode);

            if (persisted == null)
            {
                // we are always working with 2 graphs, simply add a 'persisted' one if none exists,
                // this ensures that only the changes we make within the bounds of the mapping are attempted.
                persisted = _dbContext.Set<T>().Create();
                _dbContext.Set<T>().Add(persisted);
            }

            if (_dbContext.Entry(updating).State != EntityState.Detached)
            {
                throw new InvalidOperationException("GraphDiff supports detached entities only at this time. Please try AsNoTracking() or detach your entites before calling the UpdateGraph method");
            }

            // Perform recursive update
            var entityManager = new EntityManager(_dbContext);
            var changeTracker = new ChangeTracker(_dbContext, entityManager);
            _root.Update(changeTracker, entityManager, persisted, updating);

            return persisted;
        }
        finally
        {
            _dbContext.Configuration.AutoDetectChangesEnabled = isAutoDetectEnabled;
        }
    }

I would suggest that the InvalidOperationException error message be a bit more explicit as to which entity it is which is in an attached state. Something like this:

  if (_dbContext.Entry(updating).State != EntityState.Detached)
            {
                throw new InvalidOperationException(String.Format("Entity of type {0} is in an attached state.  GraphDiff supports detached entities only at this time. Please try AsNoTracking() or detach your entites before calling the UpdateGraph method", typeof(T).FullName));
            }