Type casting in DBSet <>

Is it possible to specify a type definition in C #? For instance:

 Type t = typeof(Activity) as typeof(System.Data.Entity.DbSet<MyDomain.Activity>) 

Or an attempt to force creation:

 Type t2 = typeof(System.Data.Entity.DbSet<MyDomain.Activity>) typeof(Activity); 

I want to create a definition of type System.Data.Entity.DbSet<MyDomain.Activity>

I do this because I use reflection in my domain, trying to use context properties, in case anyone asks.

 // get types we are interested in IHit var instances = from t in Assembly.GetExecutingAssembly().GetTypes() where t.GetInterfaces().Contains(typeof(IHit)) && t.GetConstructor(Type.EmptyTypes) != null select Activator.CreateInstance(t) as IHit; // loop and cast foreach (var instance in instances) { Type t = instance.GetType() Type t2 = typeof(System.Data.Entity.DbSet<t>) as typeof(t); // do something with type 2 } 
+5
source share
1 answer

I want to create a definition of type System.Data.Entity.DbSet<MyDomain.Activity>

So you really ask t be of type System.Data.Entity.DbSet<MyDomain.Activity> . Why would you throw one type of another? The MyDomain.Activity type should not do anything with the type that you are actually requesting.

This should work for you:

 Type t = typeof(System.Data.Entity.DbSet<MyDomain.Activity>) 

If you don't already have a MyDomain.Activity type, you should use Type.MakeGenericType :

  Type dbSetType = typeof(System.Data.Entity.DbSet<>); Type t = dbSetType.MakeGenericType(yourActivityType); 
+5
source

Source: https://habr.com/ru/post/1214322/


All Articles