C#克隆System.Data.Entity.DynamicProxies到实际(非代理)类?

JK.*_*JK. 7 c# entity-framework poco dynamic-proxy cloning

可能重复:
EF4 Cast DynamicProxies到底层对象

我试图找出如何克隆或将System.Data.Entity.DynamicProxies转换为它的实际类.例如:

System.Data.Entity.DynamicProxies.Currency_F4008E27DE_etc is the proxy class
MyApp.Entities.Currency is the real class
Run Code Online (Sandbox Code Playgroud)

MyApp.Entities中的所有类都继承自BaseEntity,因此我尝试在那里进行转换:

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

然后将DynamicProxies转换为真正的类:

// 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;
Run Code Online (Sandbox Code Playgroud)

这样做的原因是我想从该对象中删除所有Entity Framework跟踪等,并将其普通(POCO)属性存储在缓存中.我需要能够为所有100个左右的Entity类执行此操作,因此它必须具有合理的通用性 - 无需为每个属性手动说出object1.foo = object2.foo.

小智 1

也许这篇文章有帮助。它讨论了克隆数据的几种方法。我不确定这些方法是否可以用于将 A 类型的对象转换为 B 类型的对象。但这绝对值得一试。

我对此结果非常感兴趣,因为这个 NuGet 包还使用通用存储库模式和 memcached 来解决相同的缓存技术,并且在反序列化数据时您的问题似乎是相同的。