Konrad Viltersten Konrad Viltersten - 1 year ago 50
C# Question

Why can't I have property of type Type in my model for Entity Framework?

I'm setting up a model for a project and everything works as expected, except for the change below. I thought it'd be neat to specify the type as

instead of its description as

namespace DataBase.Entities
public class Lock
public Guid Id { get; set; }
public DateTime? Occasion { get; set; }
public int Counter { get; set; }
public Type Entity { get; set; }
//public string Entity { get; set; }

Guess what! EF didn't like it one bit. The error I get when adding an explicit migration then is as follows and I have no idea why.

System.ArgumentNullException: Value cannot be null.

Parameter name: entitySet

Most of the goolearching resulted in people discovering that the POCO classes had some inheritance they forgot about. Someone suggested to force re-enabled migrations. I don't have any inheritance at all in the model and forcing the migrations gave nothing but a recreated configuration file.

Answer Source

I would always store the assembly-qualified type name instead of the type itself.

A Type instance it's not just a name, but a lot of metadata that may be interesting during run-time, but it would be pointless to store (i.e. serialize) a type instance as is.

When you set the whole Type property get Type.AssemblyQualifiedName property value:

instance.Type = typeof(X).AssemblyQualifiedName;

And the code that should work with the whole type could call Type.GetType(lock.Type) to build a Type instance again.