【发布时间】:2014-11-04 09:28:10
【问题描述】:
我从DbEntityEntry.Entity 获得了一个实体。这将返回实体的实体框架代理。
如何将底层对象作为其原始类型而不是代理访问?
或者,我需要动态尝试将代理转换为实体类型。这是一个开始。
var theEntityType = entityEntry.Entity;
if (
theEntityType.BaseType != null
&& entityType.Namespace == "System.Data.Entity.DynamicProxies"
)
theEntityType = entityType.BaseType;
// Now I need to cast to the correct type
// THIS WON'T WORK BECAUSE `theEntityType` is dynamic.
var entityObject = (theEntityType)entityEntry.Entity;
// My entites also don't implement IConvertible
【问题讨论】:
-
你为什么要这样做,你想达到什么目的? EF 代理继承自实际实体,那么转换回原始类型会给您带来什么?
-
@Ben 例如重载方法来处理一些实体类型。对于代理,它不适用于
checkRequired(Customer c),checkRequired(Order o) -
我更正了我的评论。如果我们有
checkRequired(Object o)(我的情况),由于代理,它将被调用而不是其他重载。但是如果Object o的重载不存在,它将调用相关方法(接受客户、订单等的方法)。不完美但至少有用。
标签: c# entity-framework