使用运行时类型的泛型类型的方法

时间:2013-01-11 05:01:44

标签: c# generics

我试图在运行时使用实体框架迁移数据库 这就是你通常会这样做的方式:

Database.SetInitializer<TContext>(new MigrateDatabaseToLatestVersion<TContext,TMigrationsConfiguration>);
            }

但是直到运行时我才知道TContext或TMigrationsConfiguration。

如何使用运行时类型执行此方法?


更新1

@Alexander Balte的建议让我使用了界面IDatabaseInitializer

所以这个编译没有错误:

foreach (IDatabaseInitializer<DbContext> initializer in moduleNeedingMigration.initializers)
{
     System.Data.Entity.Database.SetInitializer(initializer);
}

但我不能这样做:

public IEnumerable<IDatabaseInitializer<DbContext>> initializers
    {
        get
        {
            List<IDatabaseInitializer<Module1Context>> list = new List<IDatabaseInitializer<Module1Context>>();
            MigrateDatabaseToLatestVersion<Module1Context, Configuration> init = new MigrateDatabaseToLatestVersion<Module1Context, Configuration>();
            list.Add(init);
            return list;//Error cannot convert type List<IDatabaseInitializer<Module1Context>> to IEnumerable<IDatabaseInitializer<DbContext>>
        }
    }

注意 Module1Context继承DbContext


更新2

编译:

return list.Cast<IDatabaseInitializer<UpfContext>>();

然而,当我运行应用程序时,我收到了这个错误:

System.Data.Entity.MigrateDatabaseToLatestVersion`2[Module1.Models.Module1Context,Module1.Migrations.Configuration]' to type 'System.Data.Entity.IDatabaseInitializer`1[System.Data.Entity.DbContext]'.

1 个答案:

答案 0 :(得分:0)

如果你知道TContextTMigrationsConfiguration的所有可能集合,你可以创建像工厂方法一样的东西,它将通过具体类型MigrateDatabaseToLatestVersion和{{1}返回TContext }}

类似的东西:

TMigrationsConfiguration

应使用所有可能的通用参数类型集初始化Dictionary private static Dictionary<Tuple<Type, Type>, Func<object>> _map = new Dictionary<Tuple<Type, Type>, Func<object>>(); public static MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration> CreateMigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration>(TContext type, TMigrationsConfiguration configuration) { Type contextType = typeof (TContext); Type configurationType = typeof(TMigrationsConfiguration); Func<object> builder; if (!_map.TryGetValue(new Tuple<Type, Type>(contextType, configurationType), out builder)) throw new KeyNotFoundException(); return (MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration>)builder(); } 。像:

_map