c# - 如何在没有类实例的情况下获取EF动态代理类的类型

标签 c# entity-framework entity-framework-5 dynamic-proxy gettype

动态代理的名称类似于 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()

  1. 避免潜在的数据库访问
  2. 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/

相关文章:

c# - 在文档查看器中显示 XPS 文档

C#:Marshall 结构数组,其字符串从 Unity 中的 C++/ObjectiveC 到 C#

c# - 不能使用空对象或列名称。如有必要,请使用单个空格

c# - 如何在 Entity Framework 中将mysql中的char列类型作为字符串获取

c# - 遍历 Entity Framework 中的一对多关系

c# - 如何在插入失败时获取冲突行的主键?

c# - EF AssociationSet 处于已删除状态错误

asp.net-mvc - View 未将正确的信息传递给 Controller

linq - 关于 Entity Framework ,Var vs IEnumerable

testing - 如何为我的 Web 应用程序编写测试?