How to ensure proxies are created when using the repository pattern with entity framework?

Based on the answer supplied by qujck. Here is how you can do it without having to employ automapper:

Edited to always check for proxy – not just during insert – as suggested in comments

Edited again to use a different way of checking whether a proxy was passed in to the method. The reason for changing the technique is that I ran into a problem when I introduced an entity that inherited from another. In that case an inherited entity can fail the entity.e.GetType().Equals(instance.GetType() check even if it is a proxy. I got the new technique from this answer

public virtual T InsertOrUpdate(T e)
{
    DbSet<T> dbSet = Context.Set<T>();

    DbEntityEntry<T> entry;
    if (e.GetType().BaseType != null 
        && e.GetType().Namespace == "System.Data.Entity.DynamicProxies")
    {
        //The entity being added is already a proxy type that supports lazy 
        //loading - just get the context entry
        entry = Context.Entry(e);
    }
    else
    {
        //The entity being added has been created using the "new" operator. 
        //Generate a proxy type to support lazy loading  and attach it
        T instance = dbSet.Create();
        instance.ID = e.ID;
        entry = Context.Entry(instance);
        dbSet.Attach(instance);

        //and set it's values to those of the entity
        entry.CurrentValues.SetValues(e);
        e = instance;
    }

    entry.State = e.ID == default(int) ?
                            EntityState.Added :
                            EntityState.Modified;

    return e;
}

public abstract class ModelBase
{
    public int ID { get; set; }
}

Leave a Comment