Reputation: 9476
I use Entity Framework. I create Entity Model. I want to get all types of instances from DbContext in runtime.
public class MyClass
{
WdmEntities _context = = new WdmEntities();
ObjectContext objContext = ((IObjectContextAdapter)_context).ObjectContext;
EntityContainer container = objContext.MetadataWorkspace.GetEntityContainer(objContext.DefaultContainerName, DataSpace.CSpace);
//even if c=>c.FullName
List<string> nameTypes = container.BaseEntitySets.OfType<EntitySet>().Select(c=>c.Name).ToList();
List<Type> types = new List<Type>();
foreach(var name in nameTypes)
{
//.GetType return null
types.Add(Type.GetType(name));
}
}
Upvotes: 0
Views: 949
Reputation: 9476
MyContext _context = new MyContext();
ObjectContext objContext = ((IObjectContextAdapter)_context).ObjectContext;
var nameTypes = objContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Select(c => c.FullName).ToList();
List<Type> types = new List<Type>();
foreach (var name in nameTypes)
{
var type = Type.GetType(name);
types.Add(type);
}
Upvotes: 0
Reputation: 39898
Try the following:
MyContext _context = new MyContext();
ObjectContext objContext = ((IObjectContextAdapter)_context).ObjectContext;
var nameTypes = objContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace);
List<Type> types = new List<Type>();
foreach (var entityType in nameTypes)
{
var type = Type.GetType(entityType.FullName + "," + Assembly.GetExecutingAssembly().FullName);
types.Add(type);
}
By using the GetItems<EntityType>
method you directly load all your entities from the ObjectContext.
The parameter that you pass to this method specifies where you want to look for entities. You should use the OSpace
value to request entity types from the object model. This will map to CLR types except when those types are nested. In that case, you get a composed name with all the outer types in it.
Type.GetType
expects both the full name of the object and the full name of the assembly. In this example, I use Assembly.GetExecutingAssembly
. If your entities are defined in another assembly you need to change this.
Upvotes: 1