C# Clone System.Data.Entity.DynamicProxies to the actual (non proxied) class?

10,291

Maybe this article is helpful. It discusses several methods for cloning data. I'm not sure if these methods can be used to convert an object of type A to an object of type B. But it's definitely worth a try.

I would be very interested in the outcome of this, since this NuGet package also uses the generic repository pattern and memcached to address the same caching technique and your problem seems to be same there when deserializing data.

Share:
10,291
JK.
Author by

JK.

Updated on June 04, 2022

Comments

  • JK.
    JK. almost 2 years

    Possible Duplicate:
    EF4 Cast DynamicProxies to underlying object

    I'm trying to figure out how to clone or convert a System.Data.Entity.DynamicProxies into it's actual class. Eg:

    System.Data.Entity.DynamicProxies.Currency_F4008E27DE_etc is the proxy class
    MyApp.Entities.Currency is the real class
    

    All of the classes in MyApp.Entities inherit from BaseEntity, so I tried to do the converting there:

    public abstract partial class BaseEntity
    {
        public T ShallowCopy<T>() where T : BaseEntity
        {
            return this.MemberwiseClone() as T;
        }
        // other BaseEntity properties not relevent here
    }
    

    And then converting the DynamicProxies into the real class:

    // this returns a DynamicProxies class
    Currency currency = LookupDefaultCurrency(); 
    // this one needs to return a Entities.Currency class 
    // (but currently returns a DynamicProxies class too
    Currency pocoCurrency = (Currency)currency.ShallowCopy<Currency>();
    HttpRuntime.Cache[key] = pocoCurrency;
    

    The reason for this is that I want to remove all Entity Framework tracking and etc from this object and just store its plain (POCO) properties in the cache. And I will need to be able to do this for all 100 or so Entity classes, so it has to be reasonably generic - without manually saying object1.foo = object2.foo for every single property.

  • erikvda
    erikvda over 12 years
    @JK Could you provide which method made it work for you, I'm very interested, since I have the same issue in my project.