我如何声明DbContextOptionsBuilder,其中DbContext存储在一个变量中(在这种情况下,dbContext的真实名称是“ OnlineShoppingStore”,但存储在下面的两个变量中。 错误:dbContextType是一个变量,但是像类型一样使用。 最终目标是根据上述程序集中的类型声明一个新的DbContext。 示例: 答案 0 :(得分:0) 您快到了。您可以使用以下方法创建通用类型的实例: “ How to use local variable as a type? Compiler says "it is a variable but is used like a type"”是原始解决方案。var dbContextType = dbContextAssembly.GetTypes().Where(d => d.BaseType.Name == "DbContext").First();
var businessDbContext = Activator.CreateInstance(dbContextType) as DbContext;
DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder();
// Attempting Line Below
var options = new DbContextOptionsBuilder<dbContextType>().UseInMemoryDatabase(databaseName: "Test").Options;
var onlineStoreContext = new OnlineStoreContext(options)
1 个答案:
Type dbContextType = typeof(MyDbContext);
// 1st get type of Generic object
Type dbContextOptionsBuilderType = typeof(DbContextOptionsBuilder<>);
// 2nd call "MakeGenericType" method by passing the "T" type
Type dbContextOptionsBuilderGenericType = dbContextOptionsBuilderType.MakeGenericType(dbContextType);
// 3rd create an instance by using "Activator.CreateInstance"
DbContextOptionsBuilder dbContextOptionsBuilderInstance = Activator.CreateInstance(dbContextOptionsBuilderGenericType) as DbContextOptionsBuilder;
DbContextOptions dbContextOptions = dbContextOptionsBuilderInstance.UseInMemoryDatabase(databaseName: "Test").Options;