Question

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?

Was it helpful?

Solution

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:

"MyAssembly.MyEntityNamespace.MyEntity, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

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:

Type type = BuildManager.GetType("MyAssembly.MyEntityNamespace.MyEntity", false, true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top