如何声明DbContextOptionsBuilder,其中DbContext存储在变量中(在本例中,dbContext的实名为"OnlineShoppingStore“,但存储在下面的两个变量中)。
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;错误: dbContextType是一个变量,但被用作类型。
的最终目标是声明一个新的DbContext,给定来自上面程序集的类型。
示例:
var onlineStoreContext = new OnlineStoreContext(options)发布于 2019-12-31 04:43:18
你快到了。可以使用以下方法创建泛型类型的实例:
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;"How to use local variable as a type? Compiler says "it is a variable but is used like a type"“是最初的解决方案。
https://stackoverflow.com/questions/59539329
复制相似问题