Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a Type to DBSet<>

Is it possible to cast a type definition in C#? Such as the following:

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

Or trying to force a cast:

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

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

I'm doing this because I'm using reflection on my domain, trying to pull on the properties on the context, 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
}
like image 374
wonea Avatar asked Feb 27 '15 11:02

wonea


1 Answers

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

So you are actually asking t to be the type of System.Data.Entity.DbSet<MyDomain.Activity>. Why do you need to cast one type of another? The type MyDomain.Activity doesn't have to do anything with the type you are actually requesting.

This should work for you:

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

If you don't have the type of MyDomain.Activity yet, you should use Type.MakeGenericType:

 Type dbSetType = typeof(System.Data.Entity.DbSet<>);
 Type t = dbSetType.MakeGenericType(yourActivityType);
like image 189
Patrick Hofman Avatar answered Sep 30 '22 05:09

Patrick Hofman