动态代理的名称类似于 ClassName_00394CF1F92740F13E3EDBE858B6D599DFAF87AA5A089245977F61A32C75AA22
,其中 POCO 类简称为 Classname
。
我知道可以使用ObjectContext.GetObjectType(instance.GetType())
获取EF动态代理实例的POCO类型,但是有没有更简单的方法来获取给定的代理类型EF类比这个:
databaseContext.TableName.First().GetType();
因为这需要表中存在该类型的实例(通常是这种情况,但这听起来“错误”)。
我将类类型传递给函数(如下所示),以便某些父/子拖放规则可以应用于 TreeNodes(对象实例由 TreeNodes 的 Tag 属性引用,因此具有任何 EF 对象的动态类型)。
if (!AllowChildDrop(e.Node, e.TargetNode, e.DropPosition, typeof(Answer)), typeof(Question)))
那么基本上还有比这更简单的方法来获取动态类型吗?
if (!AllowChildDrop(e.Node, e.TargetNode, e.DropPosition, context.Answer.First().GetType(), context.Question.First().GetType()))
最佳答案
目前无法避免创建实例来发现运行时类型
。
您应该使用DbSet.Create()
而不是First()
- 避免潜在的数据库访问
First()
实例可能不是代理(例如,您在调用链的早期添加了一个实体)
参见here了解更多信息
[the] instance is not added or attached to the set. The instance returned will be a proxy if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy.
关于c# - 如何在没有类实例的情况下获取EF动态代理类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18822977/