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 101 forks source link

Inheritance fix @ GetOrAddPersistedEntity #97

Closed pilzandreas closed 10 years ago

pilzandreas commented 10 years ago

My colleauge Claus an me run into an error with repository's AddOrUpdate managed by GraphDiff using a base-type that hold various inherited-types.

While debugging we found GraphDiff setting up a new instance of T - to work with inherited objects of T, it is necessary to take the type of entity instead...

We suggest the following modification on V2.0.1

GraphDiffer.cs

    private T GetOrAddPersistedEntity(DbContext context, T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        var persisted = FindEntityMatching(context, entity);

        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 = Activator.CreateInstance(entity.GetType()) as T;
            //persisted = new T();
            context.Set<T>().Add(persisted);
        }

        return persisted;
    }

Thank You

Kind regards