1

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?

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

That seems obvious now that you mention it. I'll give it a shot and respond back a little later.
That was it. It didnt like the fully qualified name with version, culture and public key token, but MyAssembly.MyNamespace.MyEntity, MyAssembly worked. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.