无法使用反射创建实体框架对象的实例
我正在尝试使用反射创建实体框架对象的实例:
var type = Type.GetType("MyAssembly.MyEntityNamespace.MyEntity");
var target = Activator.CreateInstance(t);
我之前使用过此代码,它在“常规”对象上始终运行良好,但是当我在此解决方案中的 EF 对象上使用它时,GetType()
返回 null。我的 EF 模型位于其自己的单独项目中,并且此代码在其自己的单元测试程序集中执行。测试程序集确实引用了 EF 程序集,并且 EF 程序集正在将其放入 /bin 中。
我可以正常创建 EF 类的实例,但即使这种反射尝试也不起作用:
var item = new MyEntity(); //works fine
Type.GetType(item.GetType().FullName); //null
Type.GetType(item.GetType().Name); //null
我不确定这是 EF 事物还是项目引用事物。当我可以在不使用反射的情况下如此轻松地创建对象时,为什么我无法使用简单的反射来创建该对象的新实例?
I am trying to create an instance of an Entity Framework object using reflection:
var type = Type.GetType("MyAssembly.MyEntityNamespace.MyEntity");
var target = Activator.CreateInstance(t);
I have used this code before and it has always worked great on "regular" objects but when I use it on EF objects in this solution, GetType()
returns null. My EF model is in its own separate project and this code is executing in its own unit testing assembly. The test assembly does reference the EF assembly and the EF assembly is making it into the /bin.
I can create instance of the EF classes normally but even this attempt at reflection does not work:
var item = new MyEntity(); //works fine
Type.GetType(item.GetType().FullName); //null
Type.GetType(item.GetType().Name); //null
I'm not sure if this is an EF thing or a project reference thing. Why aren't I able to create a new instance of this object using simple reflection when I can create the object so easily without reflection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 EF 上下文位于不同的程序集中,因此您需要提供程序集限定名称,而不仅仅是命名空间和类型名称。
程序集限定名称看起来像这样:
如果您使用 System.Web,还有一个 BuildManager 类,它具有一些实用程序,可以根据名称更轻松地识别类:
Since the EF context is in a different assembly, you'll need to provide the assembly-qualified name, rather than just the namespace and typename.
The assembly-qualified name looks something like this:
If you are using System.Web, there is also a BuildManager class that has some utilities for more easily identifying classes based on their name: